@rspress/plugin-playground 1.11.1 → 1.11.2
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/dist/cli/cjs/index.js +3 -3
- package/dist/cli/cjs/index.js.map +1 -1
- package/dist/cli/esm/index.js +3 -3
- package/dist/cli/esm/index.js.map +1 -1
- package/dist/web/cjs/index.js +26 -15
- package/dist/web/cjs/index.js.map +1 -1
- package/dist/web/esm/index.js +26 -15
- package/dist/web/esm/index.js.map +1 -1
- package/package.json +2 -2
package/dist/cli/cjs/index.js
CHANGED
|
@@ -367,13 +367,13 @@ var remarkPlugin = ({
|
|
|
367
367
|
visit(tree, "code", (node) => {
|
|
368
368
|
if (node.lang === "jsx" || node.lang === "tsx") {
|
|
369
369
|
const hasPureMeta = node?.meta?.includes("pure");
|
|
370
|
-
const
|
|
370
|
+
const hasPlaygroundMeta = node?.meta?.includes("playground");
|
|
371
371
|
let noTransform;
|
|
372
372
|
switch (defaultRenderMode) {
|
|
373
373
|
case "pure":
|
|
374
|
-
noTransform = !
|
|
374
|
+
noTransform = !hasPlaygroundMeta;
|
|
375
375
|
break;
|
|
376
|
-
case "
|
|
376
|
+
case "playground":
|
|
377
377
|
noTransform = hasPureMeta;
|
|
378
378
|
break;
|
|
379
379
|
default:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0MA,SAAS,WAAW,OAAO;AAEzB,QAAM,SAAS,CAAC;AAChB,MAAI,QAAQ;AAEZ,SAAO,EAAE,QAAQ,MAAM,QAAQ;AAC7B,WAAO,KAAK,IAAI,QAAQ,MAAM,KAAK,CAAC;AAAA,EACtC;AAEA,SAAO,YAAY,GAAG;AAOtB,WAAS,OAAO,YAAY;AAC1B,QAAIA,SAAQ;AAEZ,WAAO,EAAEA,SAAQ,OAAO,QAAQ;AAC9B,UAAI,OAAOA,MAAK,EAAE,KAAK,MAAM,GAAG,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routeMeta","fs","code"],"sources":["../../../../../node_modules/.pnpm/unist-util-is@5.2.1/node_modules/unist-util-is/lib/index.js","../../../../../node_modules/.pnpm/unist-util-is@5.2.1/node_modules/unist-util-is/index.js","../../../../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/lib/color.js","../../../../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/lib/index.js","../../../../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/index.js","../../../../../node_modules/.pnpm/unist-util-visit@4.1.1/node_modules/unist-util-visit/index.js","../../../src/cli/index.ts","../../../src/cli/constant.ts","../../../src/cli/utils.ts","../../../src/cli/remarkPlugin.ts","../../../src/web/constant.ts","../../../src/web/utils.ts"],"sourcesContent":["/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n */\n\n/**\n * @typedef {Record<string, unknown>} Props\n * @typedef {null | undefined | string | Props | TestFunctionAnything | Array<string | Props | TestFunctionAnything>} Test\n * Check for an arbitrary node, unaware of TypeScript inferral.\n *\n * @callback TestFunctionAnything\n * Check if a node passes a test, unaware of TypeScript inferral.\n * @param {unknown} this\n * The given context.\n * @param {Node} node\n * A node.\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {boolean | void}\n * Whether this node passes the test.\n */\n\n/**\n * @template {Node} Kind\n * Node type.\n * @typedef {Kind['type'] | Partial<Kind> | TestFunctionPredicate<Kind> | Array<Kind['type'] | Partial<Kind> | TestFunctionPredicate<Kind>>} PredicateTest\n * Check for a node that can be inferred by TypeScript.\n */\n\n/**\n * Check if a node passes a certain test.\n *\n * @template {Node} Kind\n * Node type.\n * @callback TestFunctionPredicate\n * Complex test function for a node that can be inferred by TypeScript.\n * @param {Node} node\n * A node.\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {node is Kind}\n * Whether this node passes the test.\n */\n\n/**\n * @callback AssertAnything\n * Check that an arbitrary value is a node, unaware of TypeScript inferral.\n * @param {unknown} [node]\n * Anything (typically a node).\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {boolean}\n * Whether this is a node and passes a test.\n */\n\n/**\n * Check if a node is a node and passes a certain node test.\n *\n * @template {Node} Kind\n * Node type.\n * @callback AssertPredicate\n * Check that an arbitrary value is a specific node, aware of TypeScript.\n * @param {unknown} [node]\n * Anything (typically a node).\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {node is Kind}\n * Whether this is a node and passes a test.\n */\n\n/**\n * Check if `node` is a `Node` and whether it passes the given test.\n *\n * @param node\n * Thing to check, typically `Node`.\n * @param test\n * A check for a specific node.\n * @param index\n * The node’s position in its parent.\n * @param parent\n * The node’s parent.\n * @returns\n * Whether `node` is a node and passes a test.\n */\nexport const is =\n /**\n * @type {(\n * (() => false) &\n * (<Kind extends Node = Node>(node: unknown, test: PredicateTest<Kind>, index: number, parent: Parent, context?: unknown) => node is Kind) &\n * (<Kind extends Node = Node>(node: unknown, test: PredicateTest<Kind>, index?: null | undefined, parent?: null | undefined, context?: unknown) => node is Kind) &\n * ((node: unknown, test: Test, index: number, parent: Parent, context?: unknown) => boolean) &\n * ((node: unknown, test?: Test, index?: null | undefined, parent?: null | undefined, context?: unknown) => boolean)\n * )}\n */\n (\n /**\n * @param {unknown} [node]\n * @param {Test} [test]\n * @param {number | null | undefined} [index]\n * @param {Parent | null | undefined} [parent]\n * @param {unknown} [context]\n * @returns {boolean}\n */\n // eslint-disable-next-line max-params\n function is(node, test, index, parent, context) {\n const check = convert(test)\n\n if (\n index !== undefined &&\n index !== null &&\n (typeof index !== 'number' ||\n index < 0 ||\n index === Number.POSITIVE_INFINITY)\n ) {\n throw new Error('Expected positive finite index')\n }\n\n if (\n parent !== undefined &&\n parent !== null &&\n (!is(parent) || !parent.children)\n ) {\n throw new Error('Expected parent node')\n }\n\n if (\n (parent === undefined || parent === null) !==\n (index === undefined || index === null)\n ) {\n throw new Error('Expected both parent and index')\n }\n\n // @ts-expect-error Looks like a node.\n return node && node.type && typeof node.type === 'string'\n ? Boolean(check.call(context, node, index, parent))\n : false\n }\n )\n\n/**\n * Generate an assertion from a test.\n *\n * Useful if you’re going to test many nodes, for example when creating a\n * utility where something else passes a compatible test.\n *\n * The created function is a bit faster because it expects valid input only:\n * a `node`, `index`, and `parent`.\n *\n * @param test\n * * when nullish, checks if `node` is a `Node`.\n * * when `string`, works like passing `(node) => node.type === test`.\n * * when `function` checks if function passed the node is true.\n * * when `object`, checks that all keys in test are in node, and that they have (strictly) equal values.\n * * when `array`, checks if any one of the subtests pass.\n * @returns\n * An assertion.\n */\nexport const convert =\n /**\n * @type {(\n * (<Kind extends Node>(test: PredicateTest<Kind>) => AssertPredicate<Kind>) &\n * ((test?: Test) => AssertAnything)\n * )}\n */\n (\n /**\n * @param {Test} [test]\n * @returns {AssertAnything}\n */\n function (test) {\n if (test === undefined || test === null) {\n return ok\n }\n\n if (typeof test === 'string') {\n return typeFactory(test)\n }\n\n if (typeof test === 'object') {\n return Array.isArray(test) ? anyFactory(test) : propsFactory(test)\n }\n\n if (typeof test === 'function') {\n return castFactory(test)\n }\n\n throw new Error('Expected function, string, or object as test')\n }\n )\n\n/**\n * @param {Array<string | Props | TestFunctionAnything>} tests\n * @returns {AssertAnything}\n */\nfunction anyFactory(tests) {\n /** @type {Array<AssertAnything>} */\n const checks = []\n let index = -1\n\n while (++index < tests.length) {\n checks[index] = convert(tests[index])\n }\n\n return castFactory(any)\n\n /**\n * @this {unknown}\n * @param {Array<unknown>} parameters\n * @returns {boolean}\n */\n function any(...parameters) {\n let index = -1\n\n while (++index < checks.length) {\n if (checks[index].call(this, ...parameters)) return true\n }\n\n return false\n }\n}\n\n/**\n * Turn an object into a test for a node with a certain fields.\n *\n * @param {Props} check\n * @returns {AssertAnything}\n */\nfunction propsFactory(check) {\n return castFactory(all)\n\n /**\n * @param {Node} node\n * @returns {boolean}\n */\n function all(node) {\n /** @type {string} */\n let key\n\n for (key in check) {\n // @ts-expect-error: hush, it sure works as an index.\n if (node[key] !== check[key]) return false\n }\n\n return true\n }\n}\n\n/**\n * Turn a string into a test for a node with a certain type.\n *\n * @param {string} check\n * @returns {AssertAnything}\n */\nfunction typeFactory(check) {\n return castFactory(type)\n\n /**\n * @param {Node} node\n */\n function type(node) {\n return node && node.type === check\n }\n}\n\n/**\n * Turn a custom test into a test for a node that passes that test.\n *\n * @param {TestFunctionAnything} check\n * @returns {AssertAnything}\n */\nfunction castFactory(check) {\n return assertion\n\n /**\n * @this {unknown}\n * @param {unknown} node\n * @param {Array<unknown>} parameters\n * @returns {boolean}\n */\n function assertion(node, ...parameters) {\n return Boolean(\n node &&\n typeof node === 'object' &&\n 'type' in node &&\n // @ts-expect-error: fine.\n Boolean(check.call(this, node, ...parameters))\n )\n }\n}\n\nfunction ok() {\n return true\n}\n","/**\n * @typedef {import('./lib/index.js').Test} Test\n * @typedef {import('./lib/index.js').TestFunctionAnything} TestFunctionAnything\n * @typedef {import('./lib/index.js').AssertAnything} AssertAnything\n */\n\n/**\n * @template {import('unist').Node} Kind\n * @typedef {import('./lib/index.js').PredicateTest<Kind>} PredicateTest\n */\n\n/**\n * @template {import('unist').Node} Kind\n * @typedef {import('./lib/index.js').TestFunctionPredicate<Kind>} TestFunctionPredicate\n */\n\n/**\n * @template {import('unist').Node} Kind\n * @typedef {import('./lib/index.js').AssertPredicate<Kind>} AssertPredicate\n */\n\nexport {is, convert} from './lib/index.js'\n","/**\n * @param {string} d\n * @returns {string}\n */\nexport function color(d) {\n return '\\u001B[33m' + d + '\\u001B[39m'\n}\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n * @typedef {import('unist-util-is').Test} Test\n */\n\n/**\n * @typedef {boolean | 'skip'} Action\n * Union of the action types.\n *\n * @typedef {number} Index\n * Move to the sibling at `index` next (after node itself is completely\n * traversed).\n *\n * Useful if mutating the tree, such as removing the node the visitor is\n * currently on, or any of its previous siblings.\n * Results less than 0 or greater than or equal to `children.length` stop\n * traversing the parent.\n *\n * @typedef {[(Action | null | undefined | void)?, (Index | null | undefined)?]} ActionTuple\n * List with one or two values, the first an action, the second an index.\n *\n * @typedef {Action | ActionTuple | Index | null | undefined | void} VisitorResult\n * Any value that can be returned from a visitor.\n */\n\n/**\n * @template {Node} [Visited=Node]\n * Visited node type.\n * @template {Parent} [Ancestor=Parent]\n * Ancestor type.\n * @callback Visitor\n * Handle a node (matching `test`, if given).\n *\n * Visitors are free to transform `node`.\n * They can also transform the parent of node (the last of `ancestors`).\n *\n * Replacing `node` itself, if `SKIP` is not returned, still causes its\n * descendants to be walked (which is a bug).\n *\n * When adding or removing previous siblings of `node` (or next siblings, in\n * case of reverse), the `Visitor` should return a new `Index` to specify the\n * sibling to traverse after `node` is traversed.\n * Adding or removing next siblings of `node` (or previous siblings, in case\n * of reverse) is handled as expected without needing to return a new `Index`.\n *\n * Removing the children property of an ancestor still results in them being\n * traversed.\n * @param {Visited} node\n * Found node.\n * @param {Array<Ancestor>} ancestors\n * Ancestors of `node`.\n * @returns {VisitorResult}\n * What to do next.\n *\n * An `Index` is treated as a tuple of `[CONTINUE, Index]`.\n * An `Action` is treated as a tuple of `[Action]`.\n *\n * Passing a tuple back only makes sense if the `Action` is `SKIP`.\n * When the `Action` is `EXIT`, that action can be returned.\n * When the `Action` is `CONTINUE`, `Index` can be returned.\n */\n\n/**\n * @template {Node} [Tree=Node]\n * Tree type.\n * @template {Test} [Check=string]\n * Test type.\n * @typedef {Visitor<import('./complex-types.js').Matches<import('./complex-types.js').InclusiveDescendant<Tree>, Check>, Extract<import('./complex-types.js').InclusiveDescendant<Tree>, Parent>>} BuildVisitor\n * Build a typed `Visitor` function from a tree and a test.\n *\n * It will infer which values are passed as `node` and which as `parents`.\n */\n\nimport {convert} from 'unist-util-is'\nimport {color} from './color.js'\n\n/**\n * Continue traversing as normal.\n */\nexport const CONTINUE = true\n\n/**\n * Stop traversing immediately.\n */\nexport const EXIT = false\n\n/**\n * Do not traverse this node’s children.\n */\nexport const SKIP = 'skip'\n\n/**\n * Visit nodes, with ancestral information.\n *\n * This algorithm performs *depth-first* *tree traversal* in *preorder*\n * (**NLR**) or if `reverse` is given, in *reverse preorder* (**NRL**).\n *\n * You can choose for which nodes `visitor` is called by passing a `test`.\n * For complex tests, you should test yourself in `visitor`, as it will be\n * faster and will have improved type information.\n *\n * Walking the tree is an intensive task.\n * Make use of the return values of the visitor when possible.\n * Instead of walking a tree multiple times, walk it once, use `unist-util-is`\n * to check if a node matches, and then perform different operations.\n *\n * You can change the tree.\n * See `Visitor` for more info.\n *\n * @param tree\n * Tree to traverse.\n * @param test\n * `unist-util-is`-compatible test\n * @param visitor\n * Handle each node.\n * @param reverse\n * Traverse in reverse preorder (NRL) instead of the default preorder (NLR).\n * @returns\n * Nothing.\n */\nexport const visitParents =\n /**\n * @type {(\n * (<Tree extends Node, Check extends Test>(tree: Tree, test: Check, visitor: BuildVisitor<Tree, Check>, reverse?: boolean | null | undefined) => void) &\n * (<Tree extends Node>(tree: Tree, visitor: BuildVisitor<Tree>, reverse?: boolean | null | undefined) => void)\n * )}\n */\n (\n /**\n * @param {Node} tree\n * @param {Test} test\n * @param {Visitor<Node>} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {void}\n */\n function (tree, test, visitor, reverse) {\n if (typeof test === 'function' && typeof visitor !== 'function') {\n reverse = visitor\n // @ts-expect-error no visitor given, so `visitor` is test.\n visitor = test\n test = null\n }\n\n const is = convert(test)\n const step = reverse ? -1 : 1\n\n factory(tree, undefined, [])()\n\n /**\n * @param {Node} node\n * @param {number | undefined} index\n * @param {Array<Parent>} parents\n */\n function factory(node, index, parents) {\n /** @type {Record<string, unknown>} */\n // @ts-expect-error: hush\n const value = node && typeof node === 'object' ? node : {}\n\n if (typeof value.type === 'string') {\n const name =\n // `hast`\n typeof value.tagName === 'string'\n ? value.tagName\n : // `xast`\n typeof value.name === 'string'\n ? value.name\n : undefined\n\n Object.defineProperty(visit, 'name', {\n value:\n 'node (' + color(node.type + (name ? '<' + name + '>' : '')) + ')'\n })\n }\n\n return visit\n\n function visit() {\n /** @type {ActionTuple} */\n let result = []\n /** @type {ActionTuple} */\n let subresult\n /** @type {number} */\n let offset\n /** @type {Array<Parent>} */\n let grandparents\n\n if (!test || is(node, index, parents[parents.length - 1] || null)) {\n result = toResult(visitor(node, parents))\n\n if (result[0] === EXIT) {\n return result\n }\n }\n\n // @ts-expect-error looks like a parent.\n if (node.children && result[0] !== SKIP) {\n // @ts-expect-error looks like a parent.\n offset = (reverse ? node.children.length : -1) + step\n // @ts-expect-error looks like a parent.\n grandparents = parents.concat(node)\n\n // @ts-expect-error looks like a parent.\n while (offset > -1 && offset < node.children.length) {\n // @ts-expect-error looks like a parent.\n subresult = factory(node.children[offset], offset, grandparents)()\n\n if (subresult[0] === EXIT) {\n return subresult\n }\n\n offset =\n typeof subresult[1] === 'number' ? subresult[1] : offset + step\n }\n }\n\n return result\n }\n }\n }\n )\n\n/**\n * Turn a return value into a clean result.\n *\n * @param {VisitorResult} value\n * Valid return values from visitors.\n * @returns {ActionTuple}\n * Clean result.\n */\nfunction toResult(value) {\n if (Array.isArray(value)) {\n return value\n }\n\n if (typeof value === 'number') {\n return [CONTINUE, value]\n }\n\n return [value]\n}\n","// Note: types exported from `index.d.ts`\nexport {CONTINUE, EXIT, SKIP, visitParents} from './lib/index.js'\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n * @typedef {import('unist-util-is').Test} Test\n * @typedef {import('unist-util-visit-parents').VisitorResult} VisitorResult\n * @typedef {import('./complex-types.js').Visitor} Visitor\n */\n\nimport {visitParents} from 'unist-util-visit-parents'\n\n/**\n * Visit children of tree which pass test.\n *\n * @param tree\n * Tree to walk\n * @param [test]\n * `unist-util-is`-compatible test\n * @param visitor\n * Function called for nodes that pass `test`.\n * @param reverse\n * Traverse in reverse preorder (NRL) instead of preorder (NLR) (default).\n */\nexport const visit =\n /**\n * @type {(\n * (<Tree extends Node, Check extends Test>(tree: Tree, test: Check, visitor: import('./complex-types.js').BuildVisitor<Tree, Check>, reverse?: boolean) => void) &\n * (<Tree extends Node>(tree: Tree, visitor: import('./complex-types.js').BuildVisitor<Tree>, reverse?: boolean) => void)\n * )}\n */\n (\n /**\n * @param {Node} tree\n * @param {Test} test\n * @param {import('./complex-types.js').Visitor} visitor\n * @param {boolean} [reverse]\n */\n function (tree, test, visitor, reverse) {\n if (typeof test === 'function' && typeof visitor !== 'function') {\n reverse = visitor\n visitor = test\n test = null\n }\n\n visitParents(tree, test, overload, reverse)\n\n /**\n * @param {Node} node\n * @param {Array<Parent>} parents\n */\n function overload(node, parents) {\n const parent = parents[parents.length - 1]\n return visitor(\n node,\n parent ? parent.children.indexOf(node) : null,\n parent\n )\n }\n }\n )\n\nexport {CONTINUE, EXIT, SKIP} from 'unist-util-visit-parents'\n","import path, { join } from 'path';\nimport { type RouteMeta, type RspressPlugin } from '@rspress/shared';\nimport { RspackVirtualModulePlugin } from 'rspack-plugin-virtual-module';\nimport type {\n loader,\n EditorProps as MonacoEditorProps,\n} from '@monaco-editor/react';\nimport { type Code } from 'mdast';\nimport { staticPath } from './constant';\nimport { getNodeAttribute, parseImports } from './utils';\nimport { remarkPlugin } from './remarkPlugin';\nimport { DEFAULT_BABEL_URL, DEFAULT_MONACO_URL } from '@/web/constant';\nimport { normalizeUrl } from '@/web/utils';\n\ninterface PlaygroundOptions {\n render: string;\n include: Array<string | [string, string]>;\n\n defaultDirection: 'horizontal' | 'vertical';\n editorPosition: 'left' | 'right';\n\n babelUrl: string;\n\n monacoLoader: Parameters<typeof loader.config>[0];\n monacoOptions: MonacoEditorProps['options'];\n /**\n * determine how to handle a internal code block without meta\n * @default 'playground'\n */\n defaultRenderMode?: 'pure' | 'playground';\n}\n\n// eslint-disable-next-line import/no-mutable-exports\nexport let routeMeta: RouteMeta[];\n\n/**\n * The plugin is used to preview component.\n */\nexport function pluginPlayground(\n options?: Partial<PlaygroundOptions>,\n): RspressPlugin {\n const {\n render = '',\n include,\n defaultDirection = 'horizontal',\n editorPosition = 'left',\n babelUrl = '',\n monacoLoader = {},\n monacoOptions = {},\n defaultRenderMode = 'playground',\n } = options || {};\n\n const playgroundVirtualModule = new RspackVirtualModulePlugin({});\n const getRouteMeta = () => routeMeta;\n\n if (render && !/Playground\\.(jsx?|tsx?)$/.test(render)) {\n throw new Error(\n '[Playground]: render should ends with Playground.(jsx?|tsx?)',\n );\n }\n\n const preloads: string[] = [];\n const monacoPrefix = monacoLoader.paths?.vs || DEFAULT_MONACO_URL;\n preloads.push(normalizeUrl(`${monacoPrefix}/loader.js`));\n preloads.push(normalizeUrl(`${monacoPrefix}/editor/editor.main.js`));\n\n return {\n name: '@rspress/plugin-playground',\n config(config, { removePlugin }) {\n config.markdown = config.markdown || {};\n config.markdown.mdxRs = false;\n // The preview and playground plugin are mutually conflicting.\n removePlugin('@rspress/plugin-preview');\n return config;\n },\n async routeGenerated(routes: RouteMeta[]) {\n const { default: fs } = await import('@rspress/shared/fs-extra');\n\n // init routeMeta\n routeMeta = routes;\n\n const files = routes.map(route => route.absolutePath);\n\n const imports: Record<string, string> = {};\n\n // scan all demos, and generate imports\n await Promise.all(\n files.map(async (filepath, _index) => {\n const isMdxFile = /\\.mdx?$/.test(filepath);\n if (!isMdxFile) {\n return;\n }\n const { createProcessor } = await import('@mdx-js/mdx');\n const { visit } = await import('unist-util-visit');\n const { default: remarkGFM } = await import('remark-gfm');\n try {\n const processor = createProcessor({\n format: path.extname(filepath).slice(1) as 'mdx' | 'md',\n remarkPlugins: [remarkGFM],\n });\n const source = await fs.readFile(filepath, 'utf-8');\n const ast = processor.parse(source);\n\n visit(ast, 'mdxJsxFlowElement', (node: any) => {\n if (node.name === 'code') {\n const src = getNodeAttribute(node, 'src');\n if (!src) {\n return;\n }\n const demoPath = join(path.dirname(filepath), src);\n if (!fs.existsSync(demoPath)) {\n return;\n }\n\n const code = fs.readFileSync(demoPath, {\n encoding: 'utf8',\n });\n\n const thisImports = parseImports(code, path.extname(demoPath));\n thisImports.forEach(x => {\n if (typeof imports[x] === 'undefined') {\n imports[x] = x;\n }\n });\n }\n });\n\n visit(ast, 'code', (node: Code) => {\n if (node.lang === 'jsx' || node.lang === 'tsx') {\n const { value, meta } = node;\n const hasPureMeta = meta?.includes('pure');\n const hasPlaygroundMeta = meta?.includes('playground');\n\n let noTransform;\n switch (defaultRenderMode) {\n case 'pure':\n noTransform = !hasPlaygroundMeta;\n break;\n case 'playground':\n noTransform = hasPureMeta;\n break;\n default:\n break;\n }\n\n // do not anything for pure mode\n if (noTransform) {\n return;\n }\n\n const thisImports = parseImports(value, node.lang);\n thisImports.forEach(x => {\n if (typeof imports[x] === 'undefined') {\n imports[x] = x;\n }\n });\n }\n });\n } catch (e) {\n console.error(e);\n throw e;\n }\n }),\n );\n\n if (include) {\n include.forEach(item => {\n if (typeof item === 'string') {\n imports[item] = item;\n } else {\n imports[item[0]] = item[1];\n }\n });\n }\n\n if (!('react' in imports)) {\n imports.react = 'react';\n }\n\n const importKeys = Object.keys(imports);\n const code = [\n ...importKeys.map(\n (x, index) => `import * as i_${index} from '${imports[x]}';`,\n ),\n 'const imports = new Map();',\n ...importKeys.map((x, index) => `imports.set('${x}', i_${index});`),\n 'function getImport(name, getDefault) {',\n ' if (!imports.has(name)) {',\n ' throw new Error(\"Module \" + name + \" not found\");',\n ' }',\n ' const result = imports.get(name);',\n ' if (getDefault && typeof result === \"object\") {',\n ' return result.default || result;',\n ' }',\n ' return result;',\n '}',\n 'export { imports };',\n 'export default getImport;',\n ].join('\\n');\n\n // console.log('playground-imports', code);\n\n playgroundVirtualModule.writeModule('_rspress_playground_imports', code);\n },\n builderConfig: {\n source: {\n define: {\n __PLAYGROUND_DIRECTION__: JSON.stringify(defaultDirection),\n __PLAYGROUND_MONACO_LOADER__: JSON.stringify(monacoLoader),\n __PLAYGROUND_MONACO_OPTIONS__: JSON.stringify(monacoOptions),\n },\n include: [join(__dirname, '..', '..', '..')],\n },\n html: {\n tags: [\n ...preloads.map(url => ({\n tag: 'link',\n head: true,\n attrs: {\n rel: 'preload',\n href: url,\n as: 'script',\n },\n })),\n {\n tag: 'script',\n head: true,\n attrs: {\n id: 'rspress-playground-babel',\n async: true,\n src: babelUrl || DEFAULT_BABEL_URL,\n },\n },\n ],\n },\n tools: {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment, @typescript-eslint/prefer-ts-expect-error\n // @ts-ignore\n rspack: {\n plugins: [playgroundVirtualModule],\n },\n },\n },\n markdown: {\n remarkPlugins: [\n [remarkPlugin, { getRouteMeta, editorPosition, defaultRenderMode }],\n ],\n globalComponents: [\n render\n ? render\n : path.join(staticPath, 'global-components', 'Playground.tsx'),\n ],\n },\n globalStyles: path.join(staticPath, 'global-styles', 'web.css'),\n };\n}\n","import path from 'path';\n\nexport const staticPath = path.join(__dirname, '../../../static');\n","/* eslint-disable consistent-return */\nimport type { Program } from '@babel/types';\nimport oxc from '@oxidation-compiler/napi';\n\nexport const parseImports = (code: string, sourceExt: string) => {\n const parsed = oxc.parseSync(code, {\n sourceType: 'module',\n sourceFilename: `index.${sourceExt}`,\n });\n\n const ast = JSON.parse(parsed.program) as Program;\n\n const result: string[] = [];\n\n // oxc didn't have \"traverse\", so it currently only scans the first level\n // (generally, demos are not too complicated, right?)\n ast.body.forEach(statement => {\n if (statement.type === 'ImportDeclaration') {\n result.push(statement.source.value);\n }\n });\n\n return result;\n};\n\nexport const getNodeAttribute = (\n node: any,\n attrName: string,\n): string | undefined => {\n return node.attributes.find(\n (attr: { name: string; value: string }) => attr.name === attrName,\n )?.value;\n};\n\nexport const getNodeMeta = (\n node: any,\n metaName: string,\n): string | undefined => {\n if (!node.meta) {\n return;\n }\n const meta: string[] = node.meta.split(' ');\n const item: string | undefined = meta.find((x: string) =>\n x.startsWith(metaName),\n );\n if (item?.startsWith(`${metaName}=`)) {\n return item.substring(metaName.length + 1);\n }\n return item;\n};\n","import { dirname, join, resolve } from 'path';\nimport { visit } from 'unist-util-visit';\nimport fs from '@rspress/shared/fs-extra';\nimport type { RouteMeta } from '@rspress/shared';\nimport type { Plugin } from 'unified';\nimport type { Root } from 'mdast';\nimport { getNodeAttribute, getNodeMeta } from './utils';\n\nfunction createPlaygroundNode(\n currentNode: any,\n attrs: Array<[string, string]>,\n) {\n Object.assign(currentNode, {\n type: 'mdxJsxFlowElement',\n name: 'Playground',\n attributes: attrs.map(it => ({\n type: 'mdxJsxAttribute',\n name: it[0],\n value: it[1],\n })),\n });\n}\n\ninterface RemarkPluginProps {\n getRouteMeta: () => RouteMeta[];\n editorPosition: 'left' | 'right';\n defaultRenderMode: 'pure' | 'preview';\n}\n\n/**\n * remark plugin to transform code to demo\n */\nexport const remarkPlugin: Plugin<[RemarkPluginProps], Root> = ({\n getRouteMeta,\n editorPosition,\n defaultRenderMode,\n}) => {\n const routeMeta = getRouteMeta();\n\n return (tree, vfile) => {\n const route = routeMeta.find(\n meta => resolve(meta.absolutePath) === resolve((vfile.path || vfile.history[0])),\n );\n if (!route) {\n return;\n }\n\n // 1. External demo , use <code src=\"xxx\" /> to declare demo\n visit(tree, 'mdxJsxFlowElement', (node: any) => {\n if (node.name === 'code') {\n const src = getNodeAttribute(node, 'src');\n if (!src) {\n return;\n }\n const demoPath = join(dirname(route.absolutePath), src);\n if (!fs.existsSync(demoPath)) {\n return;\n }\n const direction = getNodeAttribute(node, 'direction') || '';\n const code = fs.readFileSync(demoPath, {\n encoding: 'utf8',\n });\n const language = src.substr(src.lastIndexOf('.') + 1);\n createPlaygroundNode(node, [\n ['code', code],\n ['language', language],\n ['direction', direction],\n ['editorPosition', editorPosition],\n ]);\n }\n });\n\n // 2. Internal demo, use ```j/tsx to declare demo\n visit(tree, 'code', node => {\n if (node.lang === 'jsx' || node.lang === 'tsx') {\n const hasPureMeta = node?.meta?.includes('pure');\n const hasPreviewMeta = node?.meta?.includes('preview');\n\n let noTransform;\n switch (defaultRenderMode) {\n case 'pure':\n noTransform = !hasPreviewMeta;\n break;\n case 'preview':\n noTransform = hasPureMeta;\n break;\n default:\n break;\n }\n\n // do not anything for pure mode\n if (noTransform) {\n return;\n }\n\n const direction = getNodeMeta(node, 'direction') || '';\n\n createPlaygroundNode(node, [\n ['code', node.value],\n ['language', node.lang],\n ['direction', direction],\n ['editorPosition', editorPosition],\n ]);\n }\n });\n };\n};\n","export const DEFAULT_BABEL_URL =\n 'https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.22.20/babel.min.js';\n\nexport const DEFAULT_MONACO_URL =\n 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.43.0/min/vs';\n","export function normalizeUrl(u: string) {\n return u.replace(/\\/\\//g, '/');\n}\n"]}
|
|
1
|
+
{"version":3,"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0MA,SAAS,WAAW,OAAO;AAEzB,QAAM,SAAS,CAAC;AAChB,MAAI,QAAQ;AAEZ,SAAO,EAAE,QAAQ,MAAM,QAAQ;AAC7B,WAAO,KAAK,IAAI,QAAQ,MAAM,KAAK,CAAC;AAAA,EACtC;AAEA,SAAO,YAAY,GAAG;AAOtB,WAAS,OAAO,YAAY;AAC1B,QAAIA,SAAQ;AAEZ,WAAO,EAAEA,SAAQ,OAAO,QAAQ;AAC9B,UAAI,OAAOA,MAAK,EAAE,KAAK,MAAM,GAAG,UAAU;AAAG,eAAO;AAAA,IACtD;AAEA,WAAO;AAAA,EACT;AACF;AAQA,SAAS,aAAa,OAAO;AAC3B,SAAO,YAAY,GAAG;AAMtB,WAAS,IAAI,MAAM;AAEjB,QAAI;AAEJ,SAAK,OAAO,OAAO;AAEjB,UAAI,KAAK,GAAG,MAAM,MAAM,GAAG;AAAG,eAAO;AAAA,IACvC;AAEA,WAAO;AAAA,EACT;AACF;AAQA,S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gB;AAAA,UACzD,8BAA8B,KAAK,UAAU,YAAY;AAAA,UACzD,+BAA+B,KAAK,UAAU,aAAa;AAAA,QAC7D;AAAA,QACA,SAAS,KAAC,mBAAK,WAAW,MAAM,MAAM,IAAI,CAAC;AAAA,MAC7C;AAAA,MACA,MAAM;AAAA,QACJ,MAAM;AAAA,UACJ,GAAG,SAAS,IAAI,UAAQ;AAAA,YACtB,KAAK;AAAA,YACL,MAAM;AAAA,YACN,OAAO;AAAA,cACL,KAAK;AAAA,cACL,MAAM;AAAA,cACN,IAAI;AAAA,YACN;AAAA,UACF,EAAE;AAAA,UACF;AAAA,YACE,KAAK;AAAA,YACL,MAAM;AAAA,YACN,OAAO;AAAA,cACL,IAAI;AAAA,cACJ,OAAO;AAAA,cACP,KAAK,YAAY;AAAA,YACnB;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,MACA,OAAO;AAAA;AAAA;AAAA,QAGL,QAAQ;AAAA,UACN,SAAS,CAAC,uBAAuB;AAAA,QACnC;AAAA,MACF;AAAA,IACF;AAAA,IACA,UAAU;AAAA,MACR,eAAe;AAAA,QACb,CAAC,cAAc,EAAE,cAAc,gBAAgB,kBAAkB,CAAC;AAAA,MACpE;AAAA,MACA,kBAAkB;AAAA,QAChB,SACI,SACA,aAAAE,QAAK,KAAK,YAAY,qBAAqB,gBAAgB;AAAA,MACjE;AAAA,IACF;AAAA,IACA,cAAc,aAAAA,QAAK,KAAK,YAAY,iBAAiB,SAAS;AAAA,EAChE;AACF","names":["index","init_lib","is","visit","import_path","path","oxc","routeMeta","fs","code"],"sources":["../../../../../node_modules/.pnpm/unist-util-is@5.2.1/node_modules/unist-util-is/lib/index.js","../../../../../node_modules/.pnpm/unist-util-is@5.2.1/node_modules/unist-util-is/index.js","../../../../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/lib/color.js","../../../../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/lib/index.js","../../../../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/index.js","../../../../../node_modules/.pnpm/unist-util-visit@4.1.1/node_modules/unist-util-visit/index.js","../../../src/cli/index.ts","../../../src/cli/constant.ts","../../../src/cli/utils.ts","../../../src/cli/remarkPlugin.ts","../../../src/web/constant.ts","../../../src/web/utils.ts"],"sourcesContent":["/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n */\n\n/**\n * @typedef {Record<string, unknown>} Props\n * @typedef {null | undefined | string | Props | TestFunctionAnything | Array<string | Props | TestFunctionAnything>} Test\n * Check for an arbitrary node, unaware of TypeScript inferral.\n *\n * @callback TestFunctionAnything\n * Check if a node passes a test, unaware of TypeScript inferral.\n * @param {unknown} this\n * The given context.\n * @param {Node} node\n * A node.\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {boolean | void}\n * Whether this node passes the test.\n */\n\n/**\n * @template {Node} Kind\n * Node type.\n * @typedef {Kind['type'] | Partial<Kind> | TestFunctionPredicate<Kind> | Array<Kind['type'] | Partial<Kind> | TestFunctionPredicate<Kind>>} PredicateTest\n * Check for a node that can be inferred by TypeScript.\n */\n\n/**\n * Check if a node passes a certain test.\n *\n * @template {Node} Kind\n * Node type.\n * @callback TestFunctionPredicate\n * Complex test function for a node that can be inferred by TypeScript.\n * @param {Node} node\n * A node.\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {node is Kind}\n * Whether this node passes the test.\n */\n\n/**\n * @callback AssertAnything\n * Check that an arbitrary value is a node, unaware of TypeScript inferral.\n * @param {unknown} [node]\n * Anything (typically a node).\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {boolean}\n * Whether this is a node and passes a test.\n */\n\n/**\n * Check if a node is a node and passes a certain node test.\n *\n * @template {Node} Kind\n * Node type.\n * @callback AssertPredicate\n * Check that an arbitrary value is a specific node, aware of TypeScript.\n * @param {unknown} [node]\n * Anything (typically a node).\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {node is Kind}\n * Whether this is a node and passes a test.\n */\n\n/**\n * Check if `node` is a `Node` and whether it passes the given test.\n *\n * @param node\n * Thing to check, typically `Node`.\n * @param test\n * A check for a specific node.\n * @param index\n * The node’s position in its parent.\n * @param parent\n * The node’s parent.\n * @returns\n * Whether `node` is a node and passes a test.\n */\nexport const is =\n /**\n * @type {(\n * (() => false) &\n * (<Kind extends Node = Node>(node: unknown, test: PredicateTest<Kind>, index: number, parent: Parent, context?: unknown) => node is Kind) &\n * (<Kind extends Node = Node>(node: unknown, test: PredicateTest<Kind>, index?: null | undefined, parent?: null | undefined, context?: unknown) => node is Kind) &\n * ((node: unknown, test: Test, index: number, parent: Parent, context?: unknown) => boolean) &\n * ((node: unknown, test?: Test, index?: null | undefined, parent?: null | undefined, context?: unknown) => boolean)\n * )}\n */\n (\n /**\n * @param {unknown} [node]\n * @param {Test} [test]\n * @param {number | null | undefined} [index]\n * @param {Parent | null | undefined} [parent]\n * @param {unknown} [context]\n * @returns {boolean}\n */\n // eslint-disable-next-line max-params\n function is(node, test, index, parent, context) {\n const check = convert(test)\n\n if (\n index !== undefined &&\n index !== null &&\n (typeof index !== 'number' ||\n index < 0 ||\n index === Number.POSITIVE_INFINITY)\n ) {\n throw new Error('Expected positive finite index')\n }\n\n if (\n parent !== undefined &&\n parent !== null &&\n (!is(parent) || !parent.children)\n ) {\n throw new Error('Expected parent node')\n }\n\n if (\n (parent === undefined || parent === null) !==\n (index === undefined || index === null)\n ) {\n throw new Error('Expected both parent and index')\n }\n\n // @ts-expect-error Looks like a node.\n return node && node.type && typeof node.type === 'string'\n ? Boolean(check.call(context, node, index, parent))\n : false\n }\n )\n\n/**\n * Generate an assertion from a test.\n *\n * Useful if you’re going to test many nodes, for example when creating a\n * utility where something else passes a compatible test.\n *\n * The created function is a bit faster because it expects valid input only:\n * a `node`, `index`, and `parent`.\n *\n * @param test\n * * when nullish, checks if `node` is a `Node`.\n * * when `string`, works like passing `(node) => node.type === test`.\n * * when `function` checks if function passed the node is true.\n * * when `object`, checks that all keys in test are in node, and that they have (strictly) equal values.\n * * when `array`, checks if any one of the subtests pass.\n * @returns\n * An assertion.\n */\nexport const convert =\n /**\n * @type {(\n * (<Kind extends Node>(test: PredicateTest<Kind>) => AssertPredicate<Kind>) &\n * ((test?: Test) => AssertAnything)\n * )}\n */\n (\n /**\n * @param {Test} [test]\n * @returns {AssertAnything}\n */\n function (test) {\n if (test === undefined || test === null) {\n return ok\n }\n\n if (typeof test === 'string') {\n return typeFactory(test)\n }\n\n if (typeof test === 'object') {\n return Array.isArray(test) ? anyFactory(test) : propsFactory(test)\n }\n\n if (typeof test === 'function') {\n return castFactory(test)\n }\n\n throw new Error('Expected function, string, or object as test')\n }\n )\n\n/**\n * @param {Array<string | Props | TestFunctionAnything>} tests\n * @returns {AssertAnything}\n */\nfunction anyFactory(tests) {\n /** @type {Array<AssertAnything>} */\n const checks = []\n let index = -1\n\n while (++index < tests.length) {\n checks[index] = convert(tests[index])\n }\n\n return castFactory(any)\n\n /**\n * @this {unknown}\n * @param {Array<unknown>} parameters\n * @returns {boolean}\n */\n function any(...parameters) {\n let index = -1\n\n while (++index < checks.length) {\n if (checks[index].call(this, ...parameters)) return true\n }\n\n return false\n }\n}\n\n/**\n * Turn an object into a test for a node with a certain fields.\n *\n * @param {Props} check\n * @returns {AssertAnything}\n */\nfunction propsFactory(check) {\n return castFactory(all)\n\n /**\n * @param {Node} node\n * @returns {boolean}\n */\n function all(node) {\n /** @type {string} */\n let key\n\n for (key in check) {\n // @ts-expect-error: hush, it sure works as an index.\n if (node[key] !== check[key]) return false\n }\n\n return true\n }\n}\n\n/**\n * Turn a string into a test for a node with a certain type.\n *\n * @param {string} check\n * @returns {AssertAnything}\n */\nfunction typeFactory(check) {\n return castFactory(type)\n\n /**\n * @param {Node} node\n */\n function type(node) {\n return node && node.type === check\n }\n}\n\n/**\n * Turn a custom test into a test for a node that passes that test.\n *\n * @param {TestFunctionAnything} check\n * @returns {AssertAnything}\n */\nfunction castFactory(check) {\n return assertion\n\n /**\n * @this {unknown}\n * @param {unknown} node\n * @param {Array<unknown>} parameters\n * @returns {boolean}\n */\n function assertion(node, ...parameters) {\n return Boolean(\n node &&\n typeof node === 'object' &&\n 'type' in node &&\n // @ts-expect-error: fine.\n Boolean(check.call(this, node, ...parameters))\n )\n }\n}\n\nfunction ok() {\n return true\n}\n","/**\n * @typedef {import('./lib/index.js').Test} Test\n * @typedef {import('./lib/index.js').TestFunctionAnything} TestFunctionAnything\n * @typedef {import('./lib/index.js').AssertAnything} AssertAnything\n */\n\n/**\n * @template {import('unist').Node} Kind\n * @typedef {import('./lib/index.js').PredicateTest<Kind>} PredicateTest\n */\n\n/**\n * @template {import('unist').Node} Kind\n * @typedef {import('./lib/index.js').TestFunctionPredicate<Kind>} TestFunctionPredicate\n */\n\n/**\n * @template {import('unist').Node} Kind\n * @typedef {import('./lib/index.js').AssertPredicate<Kind>} AssertPredicate\n */\n\nexport {is, convert} from './lib/index.js'\n","/**\n * @param {string} d\n * @returns {string}\n */\nexport function color(d) {\n return '\\u001B[33m' + d + '\\u001B[39m'\n}\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n * @typedef {import('unist-util-is').Test} Test\n */\n\n/**\n * @typedef {boolean | 'skip'} Action\n * Union of the action types.\n *\n * @typedef {number} Index\n * Move to the sibling at `index` next (after node itself is completely\n * traversed).\n *\n * Useful if mutating the tree, such as removing the node the visitor is\n * currently on, or any of its previous siblings.\n * Results less than 0 or greater than or equal to `children.length` stop\n * traversing the parent.\n *\n * @typedef {[(Action | null | undefined | void)?, (Index | null | undefined)?]} ActionTuple\n * List with one or two values, the first an action, the second an index.\n *\n * @typedef {Action | ActionTuple | Index | null | undefined | void} VisitorResult\n * Any value that can be returned from a visitor.\n */\n\n/**\n * @template {Node} [Visited=Node]\n * Visited node type.\n * @template {Parent} [Ancestor=Parent]\n * Ancestor type.\n * @callback Visitor\n * Handle a node (matching `test`, if given).\n *\n * Visitors are free to transform `node`.\n * They can also transform the parent of node (the last of `ancestors`).\n *\n * Replacing `node` itself, if `SKIP` is not returned, still causes its\n * descendants to be walked (which is a bug).\n *\n * When adding or removing previous siblings of `node` (or next siblings, in\n * case of reverse), the `Visitor` should return a new `Index` to specify the\n * sibling to traverse after `node` is traversed.\n * Adding or removing next siblings of `node` (or previous siblings, in case\n * of reverse) is handled as expected without needing to return a new `Index`.\n *\n * Removing the children property of an ancestor still results in them being\n * traversed.\n * @param {Visited} node\n * Found node.\n * @param {Array<Ancestor>} ancestors\n * Ancestors of `node`.\n * @returns {VisitorResult}\n * What to do next.\n *\n * An `Index` is treated as a tuple of `[CONTINUE, Index]`.\n * An `Action` is treated as a tuple of `[Action]`.\n *\n * Passing a tuple back only makes sense if the `Action` is `SKIP`.\n * When the `Action` is `EXIT`, that action can be returned.\n * When the `Action` is `CONTINUE`, `Index` can be returned.\n */\n\n/**\n * @template {Node} [Tree=Node]\n * Tree type.\n * @template {Test} [Check=string]\n * Test type.\n * @typedef {Visitor<import('./complex-types.js').Matches<import('./complex-types.js').InclusiveDescendant<Tree>, Check>, Extract<import('./complex-types.js').InclusiveDescendant<Tree>, Parent>>} BuildVisitor\n * Build a typed `Visitor` function from a tree and a test.\n *\n * It will infer which values are passed as `node` and which as `parents`.\n */\n\nimport {convert} from 'unist-util-is'\nimport {color} from './color.js'\n\n/**\n * Continue traversing as normal.\n */\nexport const CONTINUE = true\n\n/**\n * Stop traversing immediately.\n */\nexport const EXIT = false\n\n/**\n * Do not traverse this node’s children.\n */\nexport const SKIP = 'skip'\n\n/**\n * Visit nodes, with ancestral information.\n *\n * This algorithm performs *depth-first* *tree traversal* in *preorder*\n * (**NLR**) or if `reverse` is given, in *reverse preorder* (**NRL**).\n *\n * You can choose for which nodes `visitor` is called by passing a `test`.\n * For complex tests, you should test yourself in `visitor`, as it will be\n * faster and will have improved type information.\n *\n * Walking the tree is an intensive task.\n * Make use of the return values of the visitor when possible.\n * Instead of walking a tree multiple times, walk it once, use `unist-util-is`\n * to check if a node matches, and then perform different operations.\n *\n * You can change the tree.\n * See `Visitor` for more info.\n *\n * @param tree\n * Tree to traverse.\n * @param test\n * `unist-util-is`-compatible test\n * @param visitor\n * Handle each node.\n * @param reverse\n * Traverse in reverse preorder (NRL) instead of the default preorder (NLR).\n * @returns\n * Nothing.\n */\nexport const visitParents =\n /**\n * @type {(\n * (<Tree extends Node, Check extends Test>(tree: Tree, test: Check, visitor: BuildVisitor<Tree, Check>, reverse?: boolean | null | undefined) => void) &\n * (<Tree extends Node>(tree: Tree, visitor: BuildVisitor<Tree>, reverse?: boolean | null | undefined) => void)\n * )}\n */\n (\n /**\n * @param {Node} tree\n * @param {Test} test\n * @param {Visitor<Node>} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {void}\n */\n function (tree, test, visitor, reverse) {\n if (typeof test === 'function' && typeof visitor !== 'function') {\n reverse = visitor\n // @ts-expect-error no visitor given, so `visitor` is test.\n visitor = test\n test = null\n }\n\n const is = convert(test)\n const step = reverse ? -1 : 1\n\n factory(tree, undefined, [])()\n\n /**\n * @param {Node} node\n * @param {number | undefined} index\n * @param {Array<Parent>} parents\n */\n function factory(node, index, parents) {\n /** @type {Record<string, unknown>} */\n // @ts-expect-error: hush\n const value = node && typeof node === 'object' ? node : {}\n\n if (typeof value.type === 'string') {\n const name =\n // `hast`\n typeof value.tagName === 'string'\n ? value.tagName\n : // `xast`\n typeof value.name === 'string'\n ? value.name\n : undefined\n\n Object.defineProperty(visit, 'name', {\n value:\n 'node (' + color(node.type + (name ? '<' + name + '>' : '')) + ')'\n })\n }\n\n return visit\n\n function visit() {\n /** @type {ActionTuple} */\n let result = []\n /** @type {ActionTuple} */\n let subresult\n /** @type {number} */\n let offset\n /** @type {Array<Parent>} */\n let grandparents\n\n if (!test || is(node, index, parents[parents.length - 1] || null)) {\n result = toResult(visitor(node, parents))\n\n if (result[0] === EXIT) {\n return result\n }\n }\n\n // @ts-expect-error looks like a parent.\n if (node.children && result[0] !== SKIP) {\n // @ts-expect-error looks like a parent.\n offset = (reverse ? node.children.length : -1) + step\n // @ts-expect-error looks like a parent.\n grandparents = parents.concat(node)\n\n // @ts-expect-error looks like a parent.\n while (offset > -1 && offset < node.children.length) {\n // @ts-expect-error looks like a parent.\n subresult = factory(node.children[offset], offset, grandparents)()\n\n if (subresult[0] === EXIT) {\n return subresult\n }\n\n offset =\n typeof subresult[1] === 'number' ? subresult[1] : offset + step\n }\n }\n\n return result\n }\n }\n }\n )\n\n/**\n * Turn a return value into a clean result.\n *\n * @param {VisitorResult} value\n * Valid return values from visitors.\n * @returns {ActionTuple}\n * Clean result.\n */\nfunction toResult(value) {\n if (Array.isArray(value)) {\n return value\n }\n\n if (typeof value === 'number') {\n return [CONTINUE, value]\n }\n\n return [value]\n}\n","// Note: types exported from `index.d.ts`\nexport {CONTINUE, EXIT, SKIP, visitParents} from './lib/index.js'\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n * @typedef {import('unist-util-is').Test} Test\n * @typedef {import('unist-util-visit-parents').VisitorResult} VisitorResult\n * @typedef {import('./complex-types.js').Visitor} Visitor\n */\n\nimport {visitParents} from 'unist-util-visit-parents'\n\n/**\n * Visit children of tree which pass test.\n *\n * @param tree\n * Tree to walk\n * @param [test]\n * `unist-util-is`-compatible test\n * @param visitor\n * Function called for nodes that pass `test`.\n * @param reverse\n * Traverse in reverse preorder (NRL) instead of preorder (NLR) (default).\n */\nexport const visit =\n /**\n * @type {(\n * (<Tree extends Node, Check extends Test>(tree: Tree, test: Check, visitor: import('./complex-types.js').BuildVisitor<Tree, Check>, reverse?: boolean) => void) &\n * (<Tree extends Node>(tree: Tree, visitor: import('./complex-types.js').BuildVisitor<Tree>, reverse?: boolean) => void)\n * )}\n */\n (\n /**\n * @param {Node} tree\n * @param {Test} test\n * @param {import('./complex-types.js').Visitor} visitor\n * @param {boolean} [reverse]\n */\n function (tree, test, visitor, reverse) {\n if (typeof test === 'function' && typeof visitor !== 'function') {\n reverse = visitor\n visitor = test\n test = null\n }\n\n visitParents(tree, test, overload, reverse)\n\n /**\n * @param {Node} node\n * @param {Array<Parent>} parents\n */\n function overload(node, parents) {\n const parent = parents[parents.length - 1]\n return visitor(\n node,\n parent ? parent.children.indexOf(node) : null,\n parent\n )\n }\n }\n )\n\nexport {CONTINUE, EXIT, SKIP} from 'unist-util-visit-parents'\n","import path, { join } from 'path';\nimport { type RouteMeta, type RspressPlugin } from '@rspress/shared';\nimport { RspackVirtualModulePlugin } from 'rspack-plugin-virtual-module';\nimport type {\n loader,\n EditorProps as MonacoEditorProps,\n} from '@monaco-editor/react';\nimport { type Code } from 'mdast';\nimport { staticPath } from './constant';\nimport { getNodeAttribute, parseImports } from './utils';\nimport { remarkPlugin } from './remarkPlugin';\nimport { DEFAULT_BABEL_URL, DEFAULT_MONACO_URL } from '@/web/constant';\nimport { normalizeUrl } from '@/web/utils';\n\ninterface PlaygroundOptions {\n render: string;\n include: Array<string | [string, string]>;\n\n defaultDirection: 'horizontal' | 'vertical';\n editorPosition: 'left' | 'right';\n\n babelUrl: string;\n\n monacoLoader: Parameters<typeof loader.config>[0];\n monacoOptions: MonacoEditorProps['options'];\n /**\n * determine how to handle a internal code block without meta\n * @default 'playground'\n */\n defaultRenderMode?: 'pure' | 'playground';\n}\n\n// eslint-disable-next-line import/no-mutable-exports\nexport let routeMeta: RouteMeta[];\n\n/**\n * The plugin is used to preview component.\n */\nexport function pluginPlayground(\n options?: Partial<PlaygroundOptions>,\n): RspressPlugin {\n const {\n render = '',\n include,\n defaultDirection = 'horizontal',\n editorPosition = 'left',\n babelUrl = '',\n monacoLoader = {},\n monacoOptions = {},\n defaultRenderMode = 'playground',\n } = options || {};\n\n const playgroundVirtualModule = new RspackVirtualModulePlugin({});\n const getRouteMeta = () => routeMeta;\n\n if (render && !/Playground\\.(jsx?|tsx?)$/.test(render)) {\n throw new Error(\n '[Playground]: render should ends with Playground.(jsx?|tsx?)',\n );\n }\n\n const preloads: string[] = [];\n const monacoPrefix = monacoLoader.paths?.vs || DEFAULT_MONACO_URL;\n preloads.push(normalizeUrl(`${monacoPrefix}/loader.js`));\n preloads.push(normalizeUrl(`${monacoPrefix}/editor/editor.main.js`));\n\n return {\n name: '@rspress/plugin-playground',\n config(config, { removePlugin }) {\n config.markdown = config.markdown || {};\n config.markdown.mdxRs = false;\n // The preview and playground plugin are mutually conflicting.\n removePlugin('@rspress/plugin-preview');\n return config;\n },\n async routeGenerated(routes: RouteMeta[]) {\n const { default: fs } = await import('@rspress/shared/fs-extra');\n\n // init routeMeta\n routeMeta = routes;\n\n const files = routes.map(route => route.absolutePath);\n\n const imports: Record<string, string> = {};\n\n // scan all demos, and generate imports\n await Promise.all(\n files.map(async (filepath, _index) => {\n const isMdxFile = /\\.mdx?$/.test(filepath);\n if (!isMdxFile) {\n return;\n }\n const { createProcessor } = await import('@mdx-js/mdx');\n const { visit } = await import('unist-util-visit');\n const { default: remarkGFM } = await import('remark-gfm');\n try {\n const processor = createProcessor({\n format: path.extname(filepath).slice(1) as 'mdx' | 'md',\n remarkPlugins: [remarkGFM],\n });\n const source = await fs.readFile(filepath, 'utf-8');\n const ast = processor.parse(source);\n\n visit(ast, 'mdxJsxFlowElement', (node: any) => {\n if (node.name === 'code') {\n const src = getNodeAttribute(node, 'src');\n if (!src) {\n return;\n }\n const demoPath = join(path.dirname(filepath), src);\n if (!fs.existsSync(demoPath)) {\n return;\n }\n\n const code = fs.readFileSync(demoPath, {\n encoding: 'utf8',\n });\n\n const thisImports = parseImports(code, path.extname(demoPath));\n thisImports.forEach(x => {\n if (typeof imports[x] === 'undefined') {\n imports[x] = x;\n }\n });\n }\n });\n\n visit(ast, 'code', (node: Code) => {\n if (node.lang === 'jsx' || node.lang === 'tsx') {\n const { value, meta } = node;\n const hasPureMeta = meta?.includes('pure');\n const hasPlaygroundMeta = meta?.includes('playground');\n\n let noTransform;\n switch (defaultRenderMode) {\n case 'pure':\n noTransform = !hasPlaygroundMeta;\n break;\n case 'playground':\n noTransform = hasPureMeta;\n break;\n default:\n break;\n }\n\n // do not anything for pure mode\n if (noTransform) {\n return;\n }\n\n const thisImports = parseImports(value, node.lang);\n thisImports.forEach(x => {\n if (typeof imports[x] === 'undefined') {\n imports[x] = x;\n }\n });\n }\n });\n } catch (e) {\n console.error(e);\n throw e;\n }\n }),\n );\n\n if (include) {\n include.forEach(item => {\n if (typeof item === 'string') {\n imports[item] = item;\n } else {\n imports[item[0]] = item[1];\n }\n });\n }\n\n if (!('react' in imports)) {\n imports.react = 'react';\n }\n\n const importKeys = Object.keys(imports);\n const code = [\n ...importKeys.map(\n (x, index) => `import * as i_${index} from '${imports[x]}';`,\n ),\n 'const imports = new Map();',\n ...importKeys.map((x, index) => `imports.set('${x}', i_${index});`),\n 'function getImport(name, getDefault) {',\n ' if (!imports.has(name)) {',\n ' throw new Error(\"Module \" + name + \" not found\");',\n ' }',\n ' const result = imports.get(name);',\n ' if (getDefault && typeof result === \"object\") {',\n ' return result.default || result;',\n ' }',\n ' return result;',\n '}',\n 'export { imports };',\n 'export default getImport;',\n ].join('\\n');\n\n // console.log('playground-imports', code);\n\n playgroundVirtualModule.writeModule('_rspress_playground_imports', code);\n },\n builderConfig: {\n source: {\n define: {\n __PLAYGROUND_DIRECTION__: JSON.stringify(defaultDirection),\n __PLAYGROUND_MONACO_LOADER__: JSON.stringify(monacoLoader),\n __PLAYGROUND_MONACO_OPTIONS__: JSON.stringify(monacoOptions),\n },\n include: [join(__dirname, '..', '..', '..')],\n },\n html: {\n tags: [\n ...preloads.map(url => ({\n tag: 'link',\n head: true,\n attrs: {\n rel: 'preload',\n href: url,\n as: 'script',\n },\n })),\n {\n tag: 'script',\n head: true,\n attrs: {\n id: 'rspress-playground-babel',\n async: true,\n src: babelUrl || DEFAULT_BABEL_URL,\n },\n },\n ],\n },\n tools: {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment, @typescript-eslint/prefer-ts-expect-error\n // @ts-ignore\n rspack: {\n plugins: [playgroundVirtualModule],\n },\n },\n },\n markdown: {\n remarkPlugins: [\n [remarkPlugin, { getRouteMeta, editorPosition, defaultRenderMode }],\n ],\n globalComponents: [\n render\n ? render\n : path.join(staticPath, 'global-components', 'Playground.tsx'),\n ],\n },\n globalStyles: path.join(staticPath, 'global-styles', 'web.css'),\n };\n}\n","import path from 'path';\n\nexport const staticPath = path.join(__dirname, '../../../static');\n","/* eslint-disable consistent-return */\nimport type { Program } from '@babel/types';\nimport oxc from '@oxidation-compiler/napi';\n\nexport const parseImports = (code: string, sourceExt: string) => {\n const parsed = oxc.parseSync(code, {\n sourceType: 'module',\n sourceFilename: `index.${sourceExt}`,\n });\n\n const ast = JSON.parse(parsed.program) as Program;\n\n const result: string[] = [];\n\n // oxc didn't have \"traverse\", so it currently only scans the first level\n // (generally, demos are not too complicated, right?)\n ast.body.forEach(statement => {\n if (statement.type === 'ImportDeclaration') {\n result.push(statement.source.value);\n }\n });\n\n return result;\n};\n\nexport const getNodeAttribute = (\n node: any,\n attrName: string,\n): string | undefined => {\n return node.attributes.find(\n (attr: { name: string; value: string }) => attr.name === attrName,\n )?.value;\n};\n\nexport const getNodeMeta = (\n node: any,\n metaName: string,\n): string | undefined => {\n if (!node.meta) {\n return;\n }\n const meta: string[] = node.meta.split(' ');\n const item: string | undefined = meta.find((x: string) =>\n x.startsWith(metaName),\n );\n if (item?.startsWith(`${metaName}=`)) {\n return item.substring(metaName.length + 1);\n }\n return item;\n};\n","import { dirname, join, resolve } from 'path';\nimport { visit } from 'unist-util-visit';\nimport fs from '@rspress/shared/fs-extra';\nimport type { RouteMeta } from '@rspress/shared';\nimport type { Plugin } from 'unified';\nimport type { Root } from 'mdast';\nimport { getNodeAttribute, getNodeMeta } from './utils';\n\nfunction createPlaygroundNode(\n currentNode: any,\n attrs: Array<[string, string]>,\n) {\n Object.assign(currentNode, {\n type: 'mdxJsxFlowElement',\n name: 'Playground',\n attributes: attrs.map(it => ({\n type: 'mdxJsxAttribute',\n name: it[0],\n value: it[1],\n })),\n });\n}\n\ninterface RemarkPluginProps {\n getRouteMeta: () => RouteMeta[];\n editorPosition: 'left' | 'right';\n defaultRenderMode: 'pure' | 'playground';\n}\n\n/**\n * remark plugin to transform code to demo\n */\nexport const remarkPlugin: Plugin<[RemarkPluginProps], Root> = ({\n getRouteMeta,\n editorPosition,\n defaultRenderMode,\n}) => {\n const routeMeta = getRouteMeta();\n\n return (tree, vfile) => {\n const route = routeMeta.find(\n meta =>\n resolve(meta.absolutePath) === resolve(vfile.path || vfile.history[0]),\n );\n if (!route) {\n return;\n }\n\n // 1. External demo , use <code src=\"xxx\" /> to declare demo\n visit(tree, 'mdxJsxFlowElement', (node: any) => {\n if (node.name === 'code') {\n const src = getNodeAttribute(node, 'src');\n if (!src) {\n return;\n }\n const demoPath = join(dirname(route.absolutePath), src);\n if (!fs.existsSync(demoPath)) {\n return;\n }\n const direction = getNodeAttribute(node, 'direction') || '';\n const code = fs.readFileSync(demoPath, {\n encoding: 'utf8',\n });\n const language = src.substr(src.lastIndexOf('.') + 1);\n createPlaygroundNode(node, [\n ['code', code],\n ['language', language],\n ['direction', direction],\n ['editorPosition', editorPosition],\n ]);\n }\n });\n\n // 2. Internal demo, use ```j/tsx to declare demo\n visit(tree, 'code', node => {\n if (node.lang === 'jsx' || node.lang === 'tsx') {\n const hasPureMeta = node?.meta?.includes('pure');\n const hasPlaygroundMeta = node?.meta?.includes('playground');\n\n let noTransform;\n switch (defaultRenderMode) {\n case 'pure':\n noTransform = !hasPlaygroundMeta;\n break;\n case 'playground':\n noTransform = hasPureMeta;\n break;\n default:\n break;\n }\n\n // do not anything for pure mode\n if (noTransform) {\n return;\n }\n\n const direction = getNodeMeta(node, 'direction') || '';\n\n createPlaygroundNode(node, [\n ['code', node.value],\n ['language', node.lang],\n ['direction', direction],\n ['editorPosition', editorPosition],\n ]);\n }\n });\n };\n};\n","export const DEFAULT_BABEL_URL =\n 'https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.22.20/babel.min.js';\n\nexport const DEFAULT_MONACO_URL =\n 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.43.0/min/vs';\n","export function normalizeUrl(u: string) {\n return u.replace(/\\/\\//g, '/');\n}\n"]}
|
package/dist/cli/esm/index.js
CHANGED
|
@@ -339,13 +339,13 @@ var remarkPlugin = ({
|
|
|
339
339
|
visit(tree, "code", (node) => {
|
|
340
340
|
if (node.lang === "jsx" || node.lang === "tsx") {
|
|
341
341
|
const hasPureMeta = node?.meta?.includes("pure");
|
|
342
|
-
const
|
|
342
|
+
const hasPlaygroundMeta = node?.meta?.includes("playground");
|
|
343
343
|
let noTransform;
|
|
344
344
|
switch (defaultRenderMode) {
|
|
345
345
|
case "pure":
|
|
346
|
-
noTransform = !
|
|
346
|
+
noTransform = !hasPlaygroundMeta;
|
|
347
347
|
break;
|
|
348
|
-
case "
|
|
348
|
+
case "playground":
|
|
349
349
|
noTransform = hasPureMeta;
|
|
350
350
|
break;
|
|
351
351
|
default:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"mappings":";;;;;;;;;;;AA0MA,SAAS,WAAW,OAAO;AAEzB,QAAM,SAAS,CAAC;AAChB,MAAI,QAAQ;AAEZ,SAAO,EAAE,QAAQ,MAAM,QAAQ;AAC7B,WAAO,KAAK,IAAI,QAAQ,MAAM,KAAK,CAAC;AAAA,EACtC;AAEA,SAAO,YAAY,GAAG;AAOtB,WAAS,OAAO,YAAY;AAC1B,QAAIA,SAAQ;AAEZ,WAAO,EAAEA,SAAQ,OAAO,QAAQ;AAC9B,UAAI,OAAOA,MAAK,EAAE,KAAK,MAAM,GAAG,UAAU;AAAG,eAAO;AAAA,IACtD;AAEA,WAAO;AAAA,EACT;AACF;AAQA,SAAS,a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,EAAE,KAAK,IAAI;AAIX,8BAAwB,YAAY,+BAA+B,IAAI;AAAA,IACzE;AAAA,IACA,eAAe;AAAA,MACb,QAAQ;AAAA,QACN,QAAQ;AAAA,UACN,0BAA0B,KAAK,UAAU,gBAAgB;AAAA,UACzD,8BAA8B,KAAK,UAAU,YAAY;AAAA,UACzD,+BAA+B,KAAK,UAAU,aAAa;AAAA,QAC7D;AAAA,QACA,SAAS,CAACE,MAAK,WAAW,MAAM,MAAM,IAAI,CAAC;AAAA,MAC7C;AAAA,MACA,MAAM;AAAA,QACJ,MAAM;AAAA,UACJ,GAAG,SAAS,IAAI,UAAQ;AAAA,YACtB,KAAK;AAAA,YACL,MAAM;AAAA,YACN,OAAO;AAAA,cACL,KAAK;AAAA,cACL,MAAM;AAAA,cACN,IAAI;AAAA,YACN;AAAA,UACF,EAAE;AAAA,UACF;AAAA,YACE,KAAK;AAAA,YACL,MAAM;AAAA,YACN,OAAO;AAAA,cACL,IAAI;AAAA,cACJ,OAAO;AAAA,cACP,KAAK,YAAY;AAAA,YACnB;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,MACA,OAAO;AAAA;AAAA;AAAA,QAGL,QAAQ;AAAA,UACN,SAAS,CAAC,uBAAuB;AAAA,QACnC;AAAA,MACF;AAAA,IACF;AAAA,IACA,UAAU;AAAA,MACR,eAAe;AAAA,QACb,CAAC,cAAc,EAAE,cAAc,gBAAgB,kBAAkB,CAAC;AAAA,MACpE;AAAA,MACA,kBAAkB;AAAA,QAChB,SACI,SACAD,MAAK,KAAK,YAAY,qBAAqB,gBAAgB;AAAA,MACjE;AAAA,IACF;AAAA,IACA,cAAcA,MAAK,KAAK,YAAY,iBAAiB,SAAS;AAAA,EAChE;AACF","names":["index","init_lib","is","visit","path","join","routeMeta","fs","code"],"sources":["../../../../../node_modules/.pnpm/unist-util-is@5.2.1/node_modules/unist-util-is/lib/index.js","../../../../../node_modules/.pnpm/unist-util-is@5.2.1/node_modules/unist-util-is/index.js","../../../../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/lib/color.js","../../../../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/lib/index.js","../../../../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/index.js","../../../../../node_modules/.pnpm/unist-util-visit@4.1.1/node_modules/unist-util-visit/index.js","../../../src/cli/index.ts","../../../src/cli/constant.ts","../../../src/cli/utils.ts","../../../src/cli/remarkPlugin.ts","../../../src/web/constant.ts","../../../src/web/utils.ts"],"sourcesContent":["/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n */\n\n/**\n * @typedef {Record<string, unknown>} Props\n * @typedef {null | undefined | string | Props | TestFunctionAnything | Array<string | Props | TestFunctionAnything>} Test\n * Check for an arbitrary node, unaware of TypeScript inferral.\n *\n * @callback TestFunctionAnything\n * Check if a node passes a test, unaware of TypeScript inferral.\n * @param {unknown} this\n * The given context.\n * @param {Node} node\n * A node.\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {boolean | void}\n * Whether this node passes the test.\n */\n\n/**\n * @template {Node} Kind\n * Node type.\n * @typedef {Kind['type'] | Partial<Kind> | TestFunctionPredicate<Kind> | Array<Kind['type'] | Partial<Kind> | TestFunctionPredicate<Kind>>} PredicateTest\n * Check for a node that can be inferred by TypeScript.\n */\n\n/**\n * Check if a node passes a certain test.\n *\n * @template {Node} Kind\n * Node type.\n * @callback TestFunctionPredicate\n * Complex test function for a node that can be inferred by TypeScript.\n * @param {Node} node\n * A node.\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {node is Kind}\n * Whether this node passes the test.\n */\n\n/**\n * @callback AssertAnything\n * Check that an arbitrary value is a node, unaware of TypeScript inferral.\n * @param {unknown} [node]\n * Anything (typically a node).\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {boolean}\n * Whether this is a node and passes a test.\n */\n\n/**\n * Check if a node is a node and passes a certain node test.\n *\n * @template {Node} Kind\n * Node type.\n * @callback AssertPredicate\n * Check that an arbitrary value is a specific node, aware of TypeScript.\n * @param {unknown} [node]\n * Anything (typically a node).\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {node is Kind}\n * Whether this is a node and passes a test.\n */\n\n/**\n * Check if `node` is a `Node` and whether it passes the given test.\n *\n * @param node\n * Thing to check, typically `Node`.\n * @param test\n * A check for a specific node.\n * @param index\n * The node’s position in its parent.\n * @param parent\n * The node’s parent.\n * @returns\n * Whether `node` is a node and passes a test.\n */\nexport const is =\n /**\n * @type {(\n * (() => false) &\n * (<Kind extends Node = Node>(node: unknown, test: PredicateTest<Kind>, index: number, parent: Parent, context?: unknown) => node is Kind) &\n * (<Kind extends Node = Node>(node: unknown, test: PredicateTest<Kind>, index?: null | undefined, parent?: null | undefined, context?: unknown) => node is Kind) &\n * ((node: unknown, test: Test, index: number, parent: Parent, context?: unknown) => boolean) &\n * ((node: unknown, test?: Test, index?: null | undefined, parent?: null | undefined, context?: unknown) => boolean)\n * )}\n */\n (\n /**\n * @param {unknown} [node]\n * @param {Test} [test]\n * @param {number | null | undefined} [index]\n * @param {Parent | null | undefined} [parent]\n * @param {unknown} [context]\n * @returns {boolean}\n */\n // eslint-disable-next-line max-params\n function is(node, test, index, parent, context) {\n const check = convert(test)\n\n if (\n index !== undefined &&\n index !== null &&\n (typeof index !== 'number' ||\n index < 0 ||\n index === Number.POSITIVE_INFINITY)\n ) {\n throw new Error('Expected positive finite index')\n }\n\n if (\n parent !== undefined &&\n parent !== null &&\n (!is(parent) || !parent.children)\n ) {\n throw new Error('Expected parent node')\n }\n\n if (\n (parent === undefined || parent === null) !==\n (index === undefined || index === null)\n ) {\n throw new Error('Expected both parent and index')\n }\n\n // @ts-expect-error Looks like a node.\n return node && node.type && typeof node.type === 'string'\n ? Boolean(check.call(context, node, index, parent))\n : false\n }\n )\n\n/**\n * Generate an assertion from a test.\n *\n * Useful if you’re going to test many nodes, for example when creating a\n * utility where something else passes a compatible test.\n *\n * The created function is a bit faster because it expects valid input only:\n * a `node`, `index`, and `parent`.\n *\n * @param test\n * * when nullish, checks if `node` is a `Node`.\n * * when `string`, works like passing `(node) => node.type === test`.\n * * when `function` checks if function passed the node is true.\n * * when `object`, checks that all keys in test are in node, and that they have (strictly) equal values.\n * * when `array`, checks if any one of the subtests pass.\n * @returns\n * An assertion.\n */\nexport const convert =\n /**\n * @type {(\n * (<Kind extends Node>(test: PredicateTest<Kind>) => AssertPredicate<Kind>) &\n * ((test?: Test) => AssertAnything)\n * )}\n */\n (\n /**\n * @param {Test} [test]\n * @returns {AssertAnything}\n */\n function (test) {\n if (test === undefined || test === null) {\n return ok\n }\n\n if (typeof test === 'string') {\n return typeFactory(test)\n }\n\n if (typeof test === 'object') {\n return Array.isArray(test) ? anyFactory(test) : propsFactory(test)\n }\n\n if (typeof test === 'function') {\n return castFactory(test)\n }\n\n throw new Error('Expected function, string, or object as test')\n }\n )\n\n/**\n * @param {Array<string | Props | TestFunctionAnything>} tests\n * @returns {AssertAnything}\n */\nfunction anyFactory(tests) {\n /** @type {Array<AssertAnything>} */\n const checks = []\n let index = -1\n\n while (++index < tests.length) {\n checks[index] = convert(tests[index])\n }\n\n return castFactory(any)\n\n /**\n * @this {unknown}\n * @param {Array<unknown>} parameters\n * @returns {boolean}\n */\n function any(...parameters) {\n let index = -1\n\n while (++index < checks.length) {\n if (checks[index].call(this, ...parameters)) return true\n }\n\n return false\n }\n}\n\n/**\n * Turn an object into a test for a node with a certain fields.\n *\n * @param {Props} check\n * @returns {AssertAnything}\n */\nfunction propsFactory(check) {\n return castFactory(all)\n\n /**\n * @param {Node} node\n * @returns {boolean}\n */\n function all(node) {\n /** @type {string} */\n let key\n\n for (key in check) {\n // @ts-expect-error: hush, it sure works as an index.\n if (node[key] !== check[key]) return false\n }\n\n return true\n }\n}\n\n/**\n * Turn a string into a test for a node with a certain type.\n *\n * @param {string} check\n * @returns {AssertAnything}\n */\nfunction typeFactory(check) {\n return castFactory(type)\n\n /**\n * @param {Node} node\n */\n function type(node) {\n return node && node.type === check\n }\n}\n\n/**\n * Turn a custom test into a test for a node that passes that test.\n *\n * @param {TestFunctionAnything} check\n * @returns {AssertAnything}\n */\nfunction castFactory(check) {\n return assertion\n\n /**\n * @this {unknown}\n * @param {unknown} node\n * @param {Array<unknown>} parameters\n * @returns {boolean}\n */\n function assertion(node, ...parameters) {\n return Boolean(\n node &&\n typeof node === 'object' &&\n 'type' in node &&\n // @ts-expect-error: fine.\n Boolean(check.call(this, node, ...parameters))\n )\n }\n}\n\nfunction ok() {\n return true\n}\n","/**\n * @typedef {import('./lib/index.js').Test} Test\n * @typedef {import('./lib/index.js').TestFunctionAnything} TestFunctionAnything\n * @typedef {import('./lib/index.js').AssertAnything} AssertAnything\n */\n\n/**\n * @template {import('unist').Node} Kind\n * @typedef {import('./lib/index.js').PredicateTest<Kind>} PredicateTest\n */\n\n/**\n * @template {import('unist').Node} Kind\n * @typedef {import('./lib/index.js').TestFunctionPredicate<Kind>} TestFunctionPredicate\n */\n\n/**\n * @template {import('unist').Node} Kind\n * @typedef {import('./lib/index.js').AssertPredicate<Kind>} AssertPredicate\n */\n\nexport {is, convert} from './lib/index.js'\n","/**\n * @param {string} d\n * @returns {string}\n */\nexport function color(d) {\n return '\\u001B[33m' + d + '\\u001B[39m'\n}\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n * @typedef {import('unist-util-is').Test} Test\n */\n\n/**\n * @typedef {boolean | 'skip'} Action\n * Union of the action types.\n *\n * @typedef {number} Index\n * Move to the sibling at `index` next (after node itself is completely\n * traversed).\n *\n * Useful if mutating the tree, such as removing the node the visitor is\n * currently on, or any of its previous siblings.\n * Results less than 0 or greater than or equal to `children.length` stop\n * traversing the parent.\n *\n * @typedef {[(Action | null | undefined | void)?, (Index | null | undefined)?]} ActionTuple\n * List with one or two values, the first an action, the second an index.\n *\n * @typedef {Action | ActionTuple | Index | null | undefined | void} VisitorResult\n * Any value that can be returned from a visitor.\n */\n\n/**\n * @template {Node} [Visited=Node]\n * Visited node type.\n * @template {Parent} [Ancestor=Parent]\n * Ancestor type.\n * @callback Visitor\n * Handle a node (matching `test`, if given).\n *\n * Visitors are free to transform `node`.\n * They can also transform the parent of node (the last of `ancestors`).\n *\n * Replacing `node` itself, if `SKIP` is not returned, still causes its\n * descendants to be walked (which is a bug).\n *\n * When adding or removing previous siblings of `node` (or next siblings, in\n * case of reverse), the `Visitor` should return a new `Index` to specify the\n * sibling to traverse after `node` is traversed.\n * Adding or removing next siblings of `node` (or previous siblings, in case\n * of reverse) is handled as expected without needing to return a new `Index`.\n *\n * Removing the children property of an ancestor still results in them being\n * traversed.\n * @param {Visited} node\n * Found node.\n * @param {Array<Ancestor>} ancestors\n * Ancestors of `node`.\n * @returns {VisitorResult}\n * What to do next.\n *\n * An `Index` is treated as a tuple of `[CONTINUE, Index]`.\n * An `Action` is treated as a tuple of `[Action]`.\n *\n * Passing a tuple back only makes sense if the `Action` is `SKIP`.\n * When the `Action` is `EXIT`, that action can be returned.\n * When the `Action` is `CONTINUE`, `Index` can be returned.\n */\n\n/**\n * @template {Node} [Tree=Node]\n * Tree type.\n * @template {Test} [Check=string]\n * Test type.\n * @typedef {Visitor<import('./complex-types.js').Matches<import('./complex-types.js').InclusiveDescendant<Tree>, Check>, Extract<import('./complex-types.js').InclusiveDescendant<Tree>, Parent>>} BuildVisitor\n * Build a typed `Visitor` function from a tree and a test.\n *\n * It will infer which values are passed as `node` and which as `parents`.\n */\n\nimport {convert} from 'unist-util-is'\nimport {color} from './color.js'\n\n/**\n * Continue traversing as normal.\n */\nexport const CONTINUE = true\n\n/**\n * Stop traversing immediately.\n */\nexport const EXIT = false\n\n/**\n * Do not traverse this node’s children.\n */\nexport const SKIP = 'skip'\n\n/**\n * Visit nodes, with ancestral information.\n *\n * This algorithm performs *depth-first* *tree traversal* in *preorder*\n * (**NLR**) or if `reverse` is given, in *reverse preorder* (**NRL**).\n *\n * You can choose for which nodes `visitor` is called by passing a `test`.\n * For complex tests, you should test yourself in `visitor`, as it will be\n * faster and will have improved type information.\n *\n * Walking the tree is an intensive task.\n * Make use of the return values of the visitor when possible.\n * Instead of walking a tree multiple times, walk it once, use `unist-util-is`\n * to check if a node matches, and then perform different operations.\n *\n * You can change the tree.\n * See `Visitor` for more info.\n *\n * @param tree\n * Tree to traverse.\n * @param test\n * `unist-util-is`-compatible test\n * @param visitor\n * Handle each node.\n * @param reverse\n * Traverse in reverse preorder (NRL) instead of the default preorder (NLR).\n * @returns\n * Nothing.\n */\nexport const visitParents =\n /**\n * @type {(\n * (<Tree extends Node, Check extends Test>(tree: Tree, test: Check, visitor: BuildVisitor<Tree, Check>, reverse?: boolean | null | undefined) => void) &\n * (<Tree extends Node>(tree: Tree, visitor: BuildVisitor<Tree>, reverse?: boolean | null | undefined) => void)\n * )}\n */\n (\n /**\n * @param {Node} tree\n * @param {Test} test\n * @param {Visitor<Node>} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {void}\n */\n function (tree, test, visitor, reverse) {\n if (typeof test === 'function' && typeof visitor !== 'function') {\n reverse = visitor\n // @ts-expect-error no visitor given, so `visitor` is test.\n visitor = test\n test = null\n }\n\n const is = convert(test)\n const step = reverse ? -1 : 1\n\n factory(tree, undefined, [])()\n\n /**\n * @param {Node} node\n * @param {number | undefined} index\n * @param {Array<Parent>} parents\n */\n function factory(node, index, parents) {\n /** @type {Record<string, unknown>} */\n // @ts-expect-error: hush\n const value = node && typeof node === 'object' ? node : {}\n\n if (typeof value.type === 'string') {\n const name =\n // `hast`\n typeof value.tagName === 'string'\n ? value.tagName\n : // `xast`\n typeof value.name === 'string'\n ? value.name\n : undefined\n\n Object.defineProperty(visit, 'name', {\n value:\n 'node (' + color(node.type + (name ? '<' + name + '>' : '')) + ')'\n })\n }\n\n return visit\n\n function visit() {\n /** @type {ActionTuple} */\n let result = []\n /** @type {ActionTuple} */\n let subresult\n /** @type {number} */\n let offset\n /** @type {Array<Parent>} */\n let grandparents\n\n if (!test || is(node, index, parents[parents.length - 1] || null)) {\n result = toResult(visitor(node, parents))\n\n if (result[0] === EXIT) {\n return result\n }\n }\n\n // @ts-expect-error looks like a parent.\n if (node.children && result[0] !== SKIP) {\n // @ts-expect-error looks like a parent.\n offset = (reverse ? node.children.length : -1) + step\n // @ts-expect-error looks like a parent.\n grandparents = parents.concat(node)\n\n // @ts-expect-error looks like a parent.\n while (offset > -1 && offset < node.children.length) {\n // @ts-expect-error looks like a parent.\n subresult = factory(node.children[offset], offset, grandparents)()\n\n if (subresult[0] === EXIT) {\n return subresult\n }\n\n offset =\n typeof subresult[1] === 'number' ? subresult[1] : offset + step\n }\n }\n\n return result\n }\n }\n }\n )\n\n/**\n * Turn a return value into a clean result.\n *\n * @param {VisitorResult} value\n * Valid return values from visitors.\n * @returns {ActionTuple}\n * Clean result.\n */\nfunction toResult(value) {\n if (Array.isArray(value)) {\n return value\n }\n\n if (typeof value === 'number') {\n return [CONTINUE, value]\n }\n\n return [value]\n}\n","// Note: types exported from `index.d.ts`\nexport {CONTINUE, EXIT, SKIP, visitParents} from './lib/index.js'\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n * @typedef {import('unist-util-is').Test} Test\n * @typedef {import('unist-util-visit-parents').VisitorResult} VisitorResult\n * @typedef {import('./complex-types.js').Visitor} Visitor\n */\n\nimport {visitParents} from 'unist-util-visit-parents'\n\n/**\n * Visit children of tree which pass test.\n *\n * @param tree\n * Tree to walk\n * @param [test]\n * `unist-util-is`-compatible test\n * @param visitor\n * Function called for nodes that pass `test`.\n * @param reverse\n * Traverse in reverse preorder (NRL) instead of preorder (NLR) (default).\n */\nexport const visit =\n /**\n * @type {(\n * (<Tree extends Node, Check extends Test>(tree: Tree, test: Check, visitor: import('./complex-types.js').BuildVisitor<Tree, Check>, reverse?: boolean) => void) &\n * (<Tree extends Node>(tree: Tree, visitor: import('./complex-types.js').BuildVisitor<Tree>, reverse?: boolean) => void)\n * )}\n */\n (\n /**\n * @param {Node} tree\n * @param {Test} test\n * @param {import('./complex-types.js').Visitor} visitor\n * @param {boolean} [reverse]\n */\n function (tree, test, visitor, reverse) {\n if (typeof test === 'function' && typeof visitor !== 'function') {\n reverse = visitor\n visitor = test\n test = null\n }\n\n visitParents(tree, test, overload, reverse)\n\n /**\n * @param {Node} node\n * @param {Array<Parent>} parents\n */\n function overload(node, parents) {\n const parent = parents[parents.length - 1]\n return visitor(\n node,\n parent ? parent.children.indexOf(node) : null,\n parent\n )\n }\n }\n )\n\nexport {CONTINUE, EXIT, SKIP} from 'unist-util-visit-parents'\n","import path, { join } from 'path';\nimport { type RouteMeta, type RspressPlugin } from '@rspress/shared';\nimport { RspackVirtualModulePlugin } from 'rspack-plugin-virtual-module';\nimport type {\n loader,\n EditorProps as MonacoEditorProps,\n} from '@monaco-editor/react';\nimport { type Code } from 'mdast';\nimport { staticPath } from './constant';\nimport { getNodeAttribute, parseImports } from './utils';\nimport { remarkPlugin } from './remarkPlugin';\nimport { DEFAULT_BABEL_URL, DEFAULT_MONACO_URL } from '@/web/constant';\nimport { normalizeUrl } from '@/web/utils';\n\ninterface PlaygroundOptions {\n render: string;\n include: Array<string | [string, string]>;\n\n defaultDirection: 'horizontal' | 'vertical';\n editorPosition: 'left' | 'right';\n\n babelUrl: string;\n\n monacoLoader: Parameters<typeof loader.config>[0];\n monacoOptions: MonacoEditorProps['options'];\n /**\n * determine how to handle a internal code block without meta\n * @default 'playground'\n */\n defaultRenderMode?: 'pure' | 'playground';\n}\n\n// eslint-disable-next-line import/no-mutable-exports\nexport let routeMeta: RouteMeta[];\n\n/**\n * The plugin is used to preview component.\n */\nexport function pluginPlayground(\n options?: Partial<PlaygroundOptions>,\n): RspressPlugin {\n const {\n render = '',\n include,\n defaultDirection = 'horizontal',\n editorPosition = 'left',\n babelUrl = '',\n monacoLoader = {},\n monacoOptions = {},\n defaultRenderMode = 'playground',\n } = options || {};\n\n const playgroundVirtualModule = new RspackVirtualModulePlugin({});\n const getRouteMeta = () => routeMeta;\n\n if (render && !/Playground\\.(jsx?|tsx?)$/.test(render)) {\n throw new Error(\n '[Playground]: render should ends with Playground.(jsx?|tsx?)',\n );\n }\n\n const preloads: string[] = [];\n const monacoPrefix = monacoLoader.paths?.vs || DEFAULT_MONACO_URL;\n preloads.push(normalizeUrl(`${monacoPrefix}/loader.js`));\n preloads.push(normalizeUrl(`${monacoPrefix}/editor/editor.main.js`));\n\n return {\n name: '@rspress/plugin-playground',\n config(config, { removePlugin }) {\n config.markdown = config.markdown || {};\n config.markdown.mdxRs = false;\n // The preview and playground plugin are mutually conflicting.\n removePlugin('@rspress/plugin-preview');\n return config;\n },\n async routeGenerated(routes: RouteMeta[]) {\n const { default: fs } = await import('@rspress/shared/fs-extra');\n\n // init routeMeta\n routeMeta = routes;\n\n const files = routes.map(route => route.absolutePath);\n\n const imports: Record<string, string> = {};\n\n // scan all demos, and generate imports\n await Promise.all(\n files.map(async (filepath, _index) => {\n const isMdxFile = /\\.mdx?$/.test(filepath);\n if (!isMdxFile) {\n return;\n }\n const { createProcessor } = await import('@mdx-js/mdx');\n const { visit } = await import('unist-util-visit');\n const { default: remarkGFM } = await import('remark-gfm');\n try {\n const processor = createProcessor({\n format: path.extname(filepath).slice(1) as 'mdx' | 'md',\n remarkPlugins: [remarkGFM],\n });\n const source = await fs.readFile(filepath, 'utf-8');\n const ast = processor.parse(source);\n\n visit(ast, 'mdxJsxFlowElement', (node: any) => {\n if (node.name === 'code') {\n const src = getNodeAttribute(node, 'src');\n if (!src) {\n return;\n }\n const demoPath = join(path.dirname(filepath), src);\n if (!fs.existsSync(demoPath)) {\n return;\n }\n\n const code = fs.readFileSync(demoPath, {\n encoding: 'utf8',\n });\n\n const thisImports = parseImports(code, path.extname(demoPath));\n thisImports.forEach(x => {\n if (typeof imports[x] === 'undefined') {\n imports[x] = x;\n }\n });\n }\n });\n\n visit(ast, 'code', (node: Code) => {\n if (node.lang === 'jsx' || node.lang === 'tsx') {\n const { value, meta } = node;\n const hasPureMeta = meta?.includes('pure');\n const hasPlaygroundMeta = meta?.includes('playground');\n\n let noTransform;\n switch (defaultRenderMode) {\n case 'pure':\n noTransform = !hasPlaygroundMeta;\n break;\n case 'playground':\n noTransform = hasPureMeta;\n break;\n default:\n break;\n }\n\n // do not anything for pure mode\n if (noTransform) {\n return;\n }\n\n const thisImports = parseImports(value, node.lang);\n thisImports.forEach(x => {\n if (typeof imports[x] === 'undefined') {\n imports[x] = x;\n }\n });\n }\n });\n } catch (e) {\n console.error(e);\n throw e;\n }\n }),\n );\n\n if (include) {\n include.forEach(item => {\n if (typeof item === 'string') {\n imports[item] = item;\n } else {\n imports[item[0]] = item[1];\n }\n });\n }\n\n if (!('react' in imports)) {\n imports.react = 'react';\n }\n\n const importKeys = Object.keys(imports);\n const code = [\n ...importKeys.map(\n (x, index) => `import * as i_${index} from '${imports[x]}';`,\n ),\n 'const imports = new Map();',\n ...importKeys.map((x, index) => `imports.set('${x}', i_${index});`),\n 'function getImport(name, getDefault) {',\n ' if (!imports.has(name)) {',\n ' throw new Error(\"Module \" + name + \" not found\");',\n ' }',\n ' const result = imports.get(name);',\n ' if (getDefault && typeof result === \"object\") {',\n ' return result.default || result;',\n ' }',\n ' return result;',\n '}',\n 'export { imports };',\n 'export default getImport;',\n ].join('\\n');\n\n // console.log('playground-imports', code);\n\n playgroundVirtualModule.writeModule('_rspress_playground_imports', code);\n },\n builderConfig: {\n source: {\n define: {\n __PLAYGROUND_DIRECTION__: JSON.stringify(defaultDirection),\n __PLAYGROUND_MONACO_LOADER__: JSON.stringify(monacoLoader),\n __PLAYGROUND_MONACO_OPTIONS__: JSON.stringify(monacoOptions),\n },\n include: [join(__dirname, '..', '..', '..')],\n },\n html: {\n tags: [\n ...preloads.map(url => ({\n tag: 'link',\n head: true,\n attrs: {\n rel: 'preload',\n href: url,\n as: 'script',\n },\n })),\n {\n tag: 'script',\n head: true,\n attrs: {\n id: 'rspress-playground-babel',\n async: true,\n src: babelUrl || DEFAULT_BABEL_URL,\n },\n },\n ],\n },\n tools: {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment, @typescript-eslint/prefer-ts-expect-error\n // @ts-ignore\n rspack: {\n plugins: [playgroundVirtualModule],\n },\n },\n },\n markdown: {\n remarkPlugins: [\n [remarkPlugin, { getRouteMeta, editorPosition, defaultRenderMode }],\n ],\n globalComponents: [\n render\n ? render\n : path.join(staticPath, 'global-components', 'Playground.tsx'),\n ],\n },\n globalStyles: path.join(staticPath, 'global-styles', 'web.css'),\n };\n}\n","import path from 'path';\n\nexport const staticPath = path.join(__dirname, '../../../static');\n","/* eslint-disable consistent-return */\nimport type { Program } from '@babel/types';\nimport oxc from '@oxidation-compiler/napi';\n\nexport const parseImports = (code: string, sourceExt: string) => {\n const parsed = oxc.parseSync(code, {\n sourceType: 'module',\n sourceFilename: `index.${sourceExt}`,\n });\n\n const ast = JSON.parse(parsed.program) as Program;\n\n const result: string[] = [];\n\n // oxc didn't have \"traverse\", so it currently only scans the first level\n // (generally, demos are not too complicated, right?)\n ast.body.forEach(statement => {\n if (statement.type === 'ImportDeclaration') {\n result.push(statement.source.value);\n }\n });\n\n return result;\n};\n\nexport const getNodeAttribute = (\n node: any,\n attrName: string,\n): string | undefined => {\n return node.attributes.find(\n (attr: { name: string; value: string }) => attr.name === attrName,\n )?.value;\n};\n\nexport const getNodeMeta = (\n node: any,\n metaName: string,\n): string | undefined => {\n if (!node.meta) {\n return;\n }\n const meta: string[] = node.meta.split(' ');\n const item: string | undefined = meta.find((x: string) =>\n x.startsWith(metaName),\n );\n if (item?.startsWith(`${metaName}=`)) {\n return item.substring(metaName.length + 1);\n }\n return item;\n};\n","import { dirname, join, resolve } from 'path';\nimport { visit } from 'unist-util-visit';\nimport fs from '@rspress/shared/fs-extra';\nimport type { RouteMeta } from '@rspress/shared';\nimport type { Plugin } from 'unified';\nimport type { Root } from 'mdast';\nimport { getNodeAttribute, getNodeMeta } from './utils';\n\nfunction createPlaygroundNode(\n currentNode: any,\n attrs: Array<[string, string]>,\n) {\n Object.assign(currentNode, {\n type: 'mdxJsxFlowElement',\n name: 'Playground',\n attributes: attrs.map(it => ({\n type: 'mdxJsxAttribute',\n name: it[0],\n value: it[1],\n })),\n });\n}\n\ninterface RemarkPluginProps {\n getRouteMeta: () => RouteMeta[];\n editorPosition: 'left' | 'right';\n defaultRenderMode: 'pure' | 'preview';\n}\n\n/**\n * remark plugin to transform code to demo\n */\nexport const remarkPlugin: Plugin<[RemarkPluginProps], Root> = ({\n getRouteMeta,\n editorPosition,\n defaultRenderMode,\n}) => {\n const routeMeta = getRouteMeta();\n\n return (tree, vfile) => {\n const route = routeMeta.find(\n meta => resolve(meta.absolutePath) === resolve((vfile.path || vfile.history[0])),\n );\n if (!route) {\n return;\n }\n\n // 1. External demo , use <code src=\"xxx\" /> to declare demo\n visit(tree, 'mdxJsxFlowElement', (node: any) => {\n if (node.name === 'code') {\n const src = getNodeAttribute(node, 'src');\n if (!src) {\n return;\n }\n const demoPath = join(dirname(route.absolutePath), src);\n if (!fs.existsSync(demoPath)) {\n return;\n }\n const direction = getNodeAttribute(node, 'direction') || '';\n const code = fs.readFileSync(demoPath, {\n encoding: 'utf8',\n });\n const language = src.substr(src.lastIndexOf('.') + 1);\n createPlaygroundNode(node, [\n ['code', code],\n ['language', language],\n ['direction', direction],\n ['editorPosition', editorPosition],\n ]);\n }\n });\n\n // 2. Internal demo, use ```j/tsx to declare demo\n visit(tree, 'code', node => {\n if (node.lang === 'jsx' || node.lang === 'tsx') {\n const hasPureMeta = node?.meta?.includes('pure');\n const hasPreviewMeta = node?.meta?.includes('preview');\n\n let noTransform;\n switch (defaultRenderMode) {\n case 'pure':\n noTransform = !hasPreviewMeta;\n break;\n case 'preview':\n noTransform = hasPureMeta;\n break;\n default:\n break;\n }\n\n // do not anything for pure mode\n if (noTransform) {\n return;\n }\n\n const direction = getNodeMeta(node, 'direction') || '';\n\n createPlaygroundNode(node, [\n ['code', node.value],\n ['language', node.lang],\n ['direction', direction],\n ['editorPosition', editorPosition],\n ]);\n }\n });\n };\n};\n","export const DEFAULT_BABEL_URL =\n 'https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.22.20/babel.min.js';\n\nexport const DEFAULT_MONACO_URL =\n 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.43.0/min/vs';\n","export function normalizeUrl(u: string) {\n return u.replace(/\\/\\//g, '/');\n}\n"]}
|
|
1
|
+
{"version":3,"mappings":";;;;;;;;;;;AA0MA,SAAS,WAAW,OAAO;AAEzB,QAAM,SAAS,CAAC;AAChB,MAAI,QAAQ;AAEZ,SAAO,EAAE,QAAQ,MAAM,QAAQ;AAC7B,WAAO,KAAK,IAAI,QAAQ,MAAM,KAAK,CAAC;AAAA,EACtC;AAEA,SAAO,YAAY,GAAG;AAOtB,WAAS,OAAO,YAAY;AAC1B,QAAIA,SAAQ;AAEZ,WAAO,EAAEA,SAAQ,OAAO,QAAQ;AAC9B,UAAI,OAAOA,MAAK,EAAE,KAAK,MAAM,GAAG,UAAU;AAAG,eAAO;AAAA,IACtD;AAEA,WAAO;AAAA,EACT;AACF;AAQA,SAAS,aAAa,OAAO;AAC3B,SAAO,YAAY,GAAG;AAMtB,WAAS,IAAI,MAAM;AAEjB,QAAI;AAEJ,SAAK,OAAO,OAAO;AAEjB,UAAI,KAAK,GAAG,MAAM,MAAM,GAAG;AAAG,eAAO;AAAA,IACvC;AAEA,WAAO;AAAA,EACT;AACF;AAQA,SAAS,YAAY,OAAO;AAC1B,SAAO,YAAY,IAAI;AAKvB,WAAS,KAAK,MAAM;AAClB,WAAO,QAAQ,KAAK,SAAS;AAAA,EAC/B;AACF;AAQA,SAAS,YAAY,OAAO;AAC1B,SAAO;AAQP,WAAS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,GAAG,SAAS,IAAI,UAAQ;AAAA,YACtB,KAAK;AAAA,YACL,MAAM;AAAA,YACN,OAAO;AAAA,cACL,KAAK;AAAA,cACL,MAAM;AAAA,cACN,IAAI;AAAA,YACN;AAAA,UACF,EAAE;AAAA,UACF;AAAA,YACE,KAAK;AAAA,YACL,MAAM;AAAA,YACN,OAAO;AAAA,cACL,IAAI;AAAA,cACJ,OAAO;AAAA,cACP,KAAK,YAAY;AAAA,YACnB;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,MACA,OAAO;AAAA;AAAA;AAAA,QAGL,QAAQ;AAAA,UACN,SAAS,CAAC,uBAAuB;AAAA,QACnC;AAAA,MACF;AAAA,IACF;AAAA,IACA,UAAU;AAAA,MACR,eAAe;AAAA,QACb,CAAC,cAAc,EAAE,cAAc,gBAAgB,kBAAkB,CAAC;AAAA,MACpE;AAAA,MACA,kBAAkB;AAAA,QAChB,SACI,SACAD,MAAK,KAAK,YAAY,qBAAqB,gBAAgB;AAAA,MACjE;AAAA,IACF;AAAA,IACA,cAAcA,MAAK,KAAK,YAAY,iBAAiB,SAAS;AAAA,EAChE;AACF","names":["index","init_lib","is","visit","path","join","routeMeta","fs","code"],"sources":["../../../../../node_modules/.pnpm/unist-util-is@5.2.1/node_modules/unist-util-is/lib/index.js","../../../../../node_modules/.pnpm/unist-util-is@5.2.1/node_modules/unist-util-is/index.js","../../../../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/lib/color.js","../../../../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/lib/index.js","../../../../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/index.js","../../../../../node_modules/.pnpm/unist-util-visit@4.1.1/node_modules/unist-util-visit/index.js","../../../src/cli/index.ts","../../../src/cli/constant.ts","../../../src/cli/utils.ts","../../../src/cli/remarkPlugin.ts","../../../src/web/constant.ts","../../../src/web/utils.ts"],"sourcesContent":["/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n */\n\n/**\n * @typedef {Record<string, unknown>} Props\n * @typedef {null | undefined | string | Props | TestFunctionAnything | Array<string | Props | TestFunctionAnything>} Test\n * Check for an arbitrary node, unaware of TypeScript inferral.\n *\n * @callback TestFunctionAnything\n * Check if a node passes a test, unaware of TypeScript inferral.\n * @param {unknown} this\n * The given context.\n * @param {Node} node\n * A node.\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {boolean | void}\n * Whether this node passes the test.\n */\n\n/**\n * @template {Node} Kind\n * Node type.\n * @typedef {Kind['type'] | Partial<Kind> | TestFunctionPredicate<Kind> | Array<Kind['type'] | Partial<Kind> | TestFunctionPredicate<Kind>>} PredicateTest\n * Check for a node that can be inferred by TypeScript.\n */\n\n/**\n * Check if a node passes a certain test.\n *\n * @template {Node} Kind\n * Node type.\n * @callback TestFunctionPredicate\n * Complex test function for a node that can be inferred by TypeScript.\n * @param {Node} node\n * A node.\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {node is Kind}\n * Whether this node passes the test.\n */\n\n/**\n * @callback AssertAnything\n * Check that an arbitrary value is a node, unaware of TypeScript inferral.\n * @param {unknown} [node]\n * Anything (typically a node).\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {boolean}\n * Whether this is a node and passes a test.\n */\n\n/**\n * Check if a node is a node and passes a certain node test.\n *\n * @template {Node} Kind\n * Node type.\n * @callback AssertPredicate\n * Check that an arbitrary value is a specific node, aware of TypeScript.\n * @param {unknown} [node]\n * Anything (typically a node).\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {node is Kind}\n * Whether this is a node and passes a test.\n */\n\n/**\n * Check if `node` is a `Node` and whether it passes the given test.\n *\n * @param node\n * Thing to check, typically `Node`.\n * @param test\n * A check for a specific node.\n * @param index\n * The node’s position in its parent.\n * @param parent\n * The node’s parent.\n * @returns\n * Whether `node` is a node and passes a test.\n */\nexport const is =\n /**\n * @type {(\n * (() => false) &\n * (<Kind extends Node = Node>(node: unknown, test: PredicateTest<Kind>, index: number, parent: Parent, context?: unknown) => node is Kind) &\n * (<Kind extends Node = Node>(node: unknown, test: PredicateTest<Kind>, index?: null | undefined, parent?: null | undefined, context?: unknown) => node is Kind) &\n * ((node: unknown, test: Test, index: number, parent: Parent, context?: unknown) => boolean) &\n * ((node: unknown, test?: Test, index?: null | undefined, parent?: null | undefined, context?: unknown) => boolean)\n * )}\n */\n (\n /**\n * @param {unknown} [node]\n * @param {Test} [test]\n * @param {number | null | undefined} [index]\n * @param {Parent | null | undefined} [parent]\n * @param {unknown} [context]\n * @returns {boolean}\n */\n // eslint-disable-next-line max-params\n function is(node, test, index, parent, context) {\n const check = convert(test)\n\n if (\n index !== undefined &&\n index !== null &&\n (typeof index !== 'number' ||\n index < 0 ||\n index === Number.POSITIVE_INFINITY)\n ) {\n throw new Error('Expected positive finite index')\n }\n\n if (\n parent !== undefined &&\n parent !== null &&\n (!is(parent) || !parent.children)\n ) {\n throw new Error('Expected parent node')\n }\n\n if (\n (parent === undefined || parent === null) !==\n (index === undefined || index === null)\n ) {\n throw new Error('Expected both parent and index')\n }\n\n // @ts-expect-error Looks like a node.\n return node && node.type && typeof node.type === 'string'\n ? Boolean(check.call(context, node, index, parent))\n : false\n }\n )\n\n/**\n * Generate an assertion from a test.\n *\n * Useful if you’re going to test many nodes, for example when creating a\n * utility where something else passes a compatible test.\n *\n * The created function is a bit faster because it expects valid input only:\n * a `node`, `index`, and `parent`.\n *\n * @param test\n * * when nullish, checks if `node` is a `Node`.\n * * when `string`, works like passing `(node) => node.type === test`.\n * * when `function` checks if function passed the node is true.\n * * when `object`, checks that all keys in test are in node, and that they have (strictly) equal values.\n * * when `array`, checks if any one of the subtests pass.\n * @returns\n * An assertion.\n */\nexport const convert =\n /**\n * @type {(\n * (<Kind extends Node>(test: PredicateTest<Kind>) => AssertPredicate<Kind>) &\n * ((test?: Test) => AssertAnything)\n * )}\n */\n (\n /**\n * @param {Test} [test]\n * @returns {AssertAnything}\n */\n function (test) {\n if (test === undefined || test === null) {\n return ok\n }\n\n if (typeof test === 'string') {\n return typeFactory(test)\n }\n\n if (typeof test === 'object') {\n return Array.isArray(test) ? anyFactory(test) : propsFactory(test)\n }\n\n if (typeof test === 'function') {\n return castFactory(test)\n }\n\n throw new Error('Expected function, string, or object as test')\n }\n )\n\n/**\n * @param {Array<string | Props | TestFunctionAnything>} tests\n * @returns {AssertAnything}\n */\nfunction anyFactory(tests) {\n /** @type {Array<AssertAnything>} */\n const checks = []\n let index = -1\n\n while (++index < tests.length) {\n checks[index] = convert(tests[index])\n }\n\n return castFactory(any)\n\n /**\n * @this {unknown}\n * @param {Array<unknown>} parameters\n * @returns {boolean}\n */\n function any(...parameters) {\n let index = -1\n\n while (++index < checks.length) {\n if (checks[index].call(this, ...parameters)) return true\n }\n\n return false\n }\n}\n\n/**\n * Turn an object into a test for a node with a certain fields.\n *\n * @param {Props} check\n * @returns {AssertAnything}\n */\nfunction propsFactory(check) {\n return castFactory(all)\n\n /**\n * @param {Node} node\n * @returns {boolean}\n */\n function all(node) {\n /** @type {string} */\n let key\n\n for (key in check) {\n // @ts-expect-error: hush, it sure works as an index.\n if (node[key] !== check[key]) return false\n }\n\n return true\n }\n}\n\n/**\n * Turn a string into a test for a node with a certain type.\n *\n * @param {string} check\n * @returns {AssertAnything}\n */\nfunction typeFactory(check) {\n return castFactory(type)\n\n /**\n * @param {Node} node\n */\n function type(node) {\n return node && node.type === check\n }\n}\n\n/**\n * Turn a custom test into a test for a node that passes that test.\n *\n * @param {TestFunctionAnything} check\n * @returns {AssertAnything}\n */\nfunction castFactory(check) {\n return assertion\n\n /**\n * @this {unknown}\n * @param {unknown} node\n * @param {Array<unknown>} parameters\n * @returns {boolean}\n */\n function assertion(node, ...parameters) {\n return Boolean(\n node &&\n typeof node === 'object' &&\n 'type' in node &&\n // @ts-expect-error: fine.\n Boolean(check.call(this, node, ...parameters))\n )\n }\n}\n\nfunction ok() {\n return true\n}\n","/**\n * @typedef {import('./lib/index.js').Test} Test\n * @typedef {import('./lib/index.js').TestFunctionAnything} TestFunctionAnything\n * @typedef {import('./lib/index.js').AssertAnything} AssertAnything\n */\n\n/**\n * @template {import('unist').Node} Kind\n * @typedef {import('./lib/index.js').PredicateTest<Kind>} PredicateTest\n */\n\n/**\n * @template {import('unist').Node} Kind\n * @typedef {import('./lib/index.js').TestFunctionPredicate<Kind>} TestFunctionPredicate\n */\n\n/**\n * @template {import('unist').Node} Kind\n * @typedef {import('./lib/index.js').AssertPredicate<Kind>} AssertPredicate\n */\n\nexport {is, convert} from './lib/index.js'\n","/**\n * @param {string} d\n * @returns {string}\n */\nexport function color(d) {\n return '\\u001B[33m' + d + '\\u001B[39m'\n}\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n * @typedef {import('unist-util-is').Test} Test\n */\n\n/**\n * @typedef {boolean | 'skip'} Action\n * Union of the action types.\n *\n * @typedef {number} Index\n * Move to the sibling at `index` next (after node itself is completely\n * traversed).\n *\n * Useful if mutating the tree, such as removing the node the visitor is\n * currently on, or any of its previous siblings.\n * Results less than 0 or greater than or equal to `children.length` stop\n * traversing the parent.\n *\n * @typedef {[(Action | null | undefined | void)?, (Index | null | undefined)?]} ActionTuple\n * List with one or two values, the first an action, the second an index.\n *\n * @typedef {Action | ActionTuple | Index | null | undefined | void} VisitorResult\n * Any value that can be returned from a visitor.\n */\n\n/**\n * @template {Node} [Visited=Node]\n * Visited node type.\n * @template {Parent} [Ancestor=Parent]\n * Ancestor type.\n * @callback Visitor\n * Handle a node (matching `test`, if given).\n *\n * Visitors are free to transform `node`.\n * They can also transform the parent of node (the last of `ancestors`).\n *\n * Replacing `node` itself, if `SKIP` is not returned, still causes its\n * descendants to be walked (which is a bug).\n *\n * When adding or removing previous siblings of `node` (or next siblings, in\n * case of reverse), the `Visitor` should return a new `Index` to specify the\n * sibling to traverse after `node` is traversed.\n * Adding or removing next siblings of `node` (or previous siblings, in case\n * of reverse) is handled as expected without needing to return a new `Index`.\n *\n * Removing the children property of an ancestor still results in them being\n * traversed.\n * @param {Visited} node\n * Found node.\n * @param {Array<Ancestor>} ancestors\n * Ancestors of `node`.\n * @returns {VisitorResult}\n * What to do next.\n *\n * An `Index` is treated as a tuple of `[CONTINUE, Index]`.\n * An `Action` is treated as a tuple of `[Action]`.\n *\n * Passing a tuple back only makes sense if the `Action` is `SKIP`.\n * When the `Action` is `EXIT`, that action can be returned.\n * When the `Action` is `CONTINUE`, `Index` can be returned.\n */\n\n/**\n * @template {Node} [Tree=Node]\n * Tree type.\n * @template {Test} [Check=string]\n * Test type.\n * @typedef {Visitor<import('./complex-types.js').Matches<import('./complex-types.js').InclusiveDescendant<Tree>, Check>, Extract<import('./complex-types.js').InclusiveDescendant<Tree>, Parent>>} BuildVisitor\n * Build a typed `Visitor` function from a tree and a test.\n *\n * It will infer which values are passed as `node` and which as `parents`.\n */\n\nimport {convert} from 'unist-util-is'\nimport {color} from './color.js'\n\n/**\n * Continue traversing as normal.\n */\nexport const CONTINUE = true\n\n/**\n * Stop traversing immediately.\n */\nexport const EXIT = false\n\n/**\n * Do not traverse this node’s children.\n */\nexport const SKIP = 'skip'\n\n/**\n * Visit nodes, with ancestral information.\n *\n * This algorithm performs *depth-first* *tree traversal* in *preorder*\n * (**NLR**) or if `reverse` is given, in *reverse preorder* (**NRL**).\n *\n * You can choose for which nodes `visitor` is called by passing a `test`.\n * For complex tests, you should test yourself in `visitor`, as it will be\n * faster and will have improved type information.\n *\n * Walking the tree is an intensive task.\n * Make use of the return values of the visitor when possible.\n * Instead of walking a tree multiple times, walk it once, use `unist-util-is`\n * to check if a node matches, and then perform different operations.\n *\n * You can change the tree.\n * See `Visitor` for more info.\n *\n * @param tree\n * Tree to traverse.\n * @param test\n * `unist-util-is`-compatible test\n * @param visitor\n * Handle each node.\n * @param reverse\n * Traverse in reverse preorder (NRL) instead of the default preorder (NLR).\n * @returns\n * Nothing.\n */\nexport const visitParents =\n /**\n * @type {(\n * (<Tree extends Node, Check extends Test>(tree: Tree, test: Check, visitor: BuildVisitor<Tree, Check>, reverse?: boolean | null | undefined) => void) &\n * (<Tree extends Node>(tree: Tree, visitor: BuildVisitor<Tree>, reverse?: boolean | null | undefined) => void)\n * )}\n */\n (\n /**\n * @param {Node} tree\n * @param {Test} test\n * @param {Visitor<Node>} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {void}\n */\n function (tree, test, visitor, reverse) {\n if (typeof test === 'function' && typeof visitor !== 'function') {\n reverse = visitor\n // @ts-expect-error no visitor given, so `visitor` is test.\n visitor = test\n test = null\n }\n\n const is = convert(test)\n const step = reverse ? -1 : 1\n\n factory(tree, undefined, [])()\n\n /**\n * @param {Node} node\n * @param {number | undefined} index\n * @param {Array<Parent>} parents\n */\n function factory(node, index, parents) {\n /** @type {Record<string, unknown>} */\n // @ts-expect-error: hush\n const value = node && typeof node === 'object' ? node : {}\n\n if (typeof value.type === 'string') {\n const name =\n // `hast`\n typeof value.tagName === 'string'\n ? value.tagName\n : // `xast`\n typeof value.name === 'string'\n ? value.name\n : undefined\n\n Object.defineProperty(visit, 'name', {\n value:\n 'node (' + color(node.type + (name ? '<' + name + '>' : '')) + ')'\n })\n }\n\n return visit\n\n function visit() {\n /** @type {ActionTuple} */\n let result = []\n /** @type {ActionTuple} */\n let subresult\n /** @type {number} */\n let offset\n /** @type {Array<Parent>} */\n let grandparents\n\n if (!test || is(node, index, parents[parents.length - 1] || null)) {\n result = toResult(visitor(node, parents))\n\n if (result[0] === EXIT) {\n return result\n }\n }\n\n // @ts-expect-error looks like a parent.\n if (node.children && result[0] !== SKIP) {\n // @ts-expect-error looks like a parent.\n offset = (reverse ? node.children.length : -1) + step\n // @ts-expect-error looks like a parent.\n grandparents = parents.concat(node)\n\n // @ts-expect-error looks like a parent.\n while (offset > -1 && offset < node.children.length) {\n // @ts-expect-error looks like a parent.\n subresult = factory(node.children[offset], offset, grandparents)()\n\n if (subresult[0] === EXIT) {\n return subresult\n }\n\n offset =\n typeof subresult[1] === 'number' ? subresult[1] : offset + step\n }\n }\n\n return result\n }\n }\n }\n )\n\n/**\n * Turn a return value into a clean result.\n *\n * @param {VisitorResult} value\n * Valid return values from visitors.\n * @returns {ActionTuple}\n * Clean result.\n */\nfunction toResult(value) {\n if (Array.isArray(value)) {\n return value\n }\n\n if (typeof value === 'number') {\n return [CONTINUE, value]\n }\n\n return [value]\n}\n","// Note: types exported from `index.d.ts`\nexport {CONTINUE, EXIT, SKIP, visitParents} from './lib/index.js'\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n * @typedef {import('unist-util-is').Test} Test\n * @typedef {import('unist-util-visit-parents').VisitorResult} VisitorResult\n * @typedef {import('./complex-types.js').Visitor} Visitor\n */\n\nimport {visitParents} from 'unist-util-visit-parents'\n\n/**\n * Visit children of tree which pass test.\n *\n * @param tree\n * Tree to walk\n * @param [test]\n * `unist-util-is`-compatible test\n * @param visitor\n * Function called for nodes that pass `test`.\n * @param reverse\n * Traverse in reverse preorder (NRL) instead of preorder (NLR) (default).\n */\nexport const visit =\n /**\n * @type {(\n * (<Tree extends Node, Check extends Test>(tree: Tree, test: Check, visitor: import('./complex-types.js').BuildVisitor<Tree, Check>, reverse?: boolean) => void) &\n * (<Tree extends Node>(tree: Tree, visitor: import('./complex-types.js').BuildVisitor<Tree>, reverse?: boolean) => void)\n * )}\n */\n (\n /**\n * @param {Node} tree\n * @param {Test} test\n * @param {import('./complex-types.js').Visitor} visitor\n * @param {boolean} [reverse]\n */\n function (tree, test, visitor, reverse) {\n if (typeof test === 'function' && typeof visitor !== 'function') {\n reverse = visitor\n visitor = test\n test = null\n }\n\n visitParents(tree, test, overload, reverse)\n\n /**\n * @param {Node} node\n * @param {Array<Parent>} parents\n */\n function overload(node, parents) {\n const parent = parents[parents.length - 1]\n return visitor(\n node,\n parent ? parent.children.indexOf(node) : null,\n parent\n )\n }\n }\n )\n\nexport {CONTINUE, EXIT, SKIP} from 'unist-util-visit-parents'\n","import path, { join } from 'path';\nimport { type RouteMeta, type RspressPlugin } from '@rspress/shared';\nimport { RspackVirtualModulePlugin } from 'rspack-plugin-virtual-module';\nimport type {\n loader,\n EditorProps as MonacoEditorProps,\n} from '@monaco-editor/react';\nimport { type Code } from 'mdast';\nimport { staticPath } from './constant';\nimport { getNodeAttribute, parseImports } from './utils';\nimport { remarkPlugin } from './remarkPlugin';\nimport { DEFAULT_BABEL_URL, DEFAULT_MONACO_URL } from '@/web/constant';\nimport { normalizeUrl } from '@/web/utils';\n\ninterface PlaygroundOptions {\n render: string;\n include: Array<string | [string, string]>;\n\n defaultDirection: 'horizontal' | 'vertical';\n editorPosition: 'left' | 'right';\n\n babelUrl: string;\n\n monacoLoader: Parameters<typeof loader.config>[0];\n monacoOptions: MonacoEditorProps['options'];\n /**\n * determine how to handle a internal code block without meta\n * @default 'playground'\n */\n defaultRenderMode?: 'pure' | 'playground';\n}\n\n// eslint-disable-next-line import/no-mutable-exports\nexport let routeMeta: RouteMeta[];\n\n/**\n * The plugin is used to preview component.\n */\nexport function pluginPlayground(\n options?: Partial<PlaygroundOptions>,\n): RspressPlugin {\n const {\n render = '',\n include,\n defaultDirection = 'horizontal',\n editorPosition = 'left',\n babelUrl = '',\n monacoLoader = {},\n monacoOptions = {},\n defaultRenderMode = 'playground',\n } = options || {};\n\n const playgroundVirtualModule = new RspackVirtualModulePlugin({});\n const getRouteMeta = () => routeMeta;\n\n if (render && !/Playground\\.(jsx?|tsx?)$/.test(render)) {\n throw new Error(\n '[Playground]: render should ends with Playground.(jsx?|tsx?)',\n );\n }\n\n const preloads: string[] = [];\n const monacoPrefix = monacoLoader.paths?.vs || DEFAULT_MONACO_URL;\n preloads.push(normalizeUrl(`${monacoPrefix}/loader.js`));\n preloads.push(normalizeUrl(`${monacoPrefix}/editor/editor.main.js`));\n\n return {\n name: '@rspress/plugin-playground',\n config(config, { removePlugin }) {\n config.markdown = config.markdown || {};\n config.markdown.mdxRs = false;\n // The preview and playground plugin are mutually conflicting.\n removePlugin('@rspress/plugin-preview');\n return config;\n },\n async routeGenerated(routes: RouteMeta[]) {\n const { default: fs } = await import('@rspress/shared/fs-extra');\n\n // init routeMeta\n routeMeta = routes;\n\n const files = routes.map(route => route.absolutePath);\n\n const imports: Record<string, string> = {};\n\n // scan all demos, and generate imports\n await Promise.all(\n files.map(async (filepath, _index) => {\n const isMdxFile = /\\.mdx?$/.test(filepath);\n if (!isMdxFile) {\n return;\n }\n const { createProcessor } = await import('@mdx-js/mdx');\n const { visit } = await import('unist-util-visit');\n const { default: remarkGFM } = await import('remark-gfm');\n try {\n const processor = createProcessor({\n format: path.extname(filepath).slice(1) as 'mdx' | 'md',\n remarkPlugins: [remarkGFM],\n });\n const source = await fs.readFile(filepath, 'utf-8');\n const ast = processor.parse(source);\n\n visit(ast, 'mdxJsxFlowElement', (node: any) => {\n if (node.name === 'code') {\n const src = getNodeAttribute(node, 'src');\n if (!src) {\n return;\n }\n const demoPath = join(path.dirname(filepath), src);\n if (!fs.existsSync(demoPath)) {\n return;\n }\n\n const code = fs.readFileSync(demoPath, {\n encoding: 'utf8',\n });\n\n const thisImports = parseImports(code, path.extname(demoPath));\n thisImports.forEach(x => {\n if (typeof imports[x] === 'undefined') {\n imports[x] = x;\n }\n });\n }\n });\n\n visit(ast, 'code', (node: Code) => {\n if (node.lang === 'jsx' || node.lang === 'tsx') {\n const { value, meta } = node;\n const hasPureMeta = meta?.includes('pure');\n const hasPlaygroundMeta = meta?.includes('playground');\n\n let noTransform;\n switch (defaultRenderMode) {\n case 'pure':\n noTransform = !hasPlaygroundMeta;\n break;\n case 'playground':\n noTransform = hasPureMeta;\n break;\n default:\n break;\n }\n\n // do not anything for pure mode\n if (noTransform) {\n return;\n }\n\n const thisImports = parseImports(value, node.lang);\n thisImports.forEach(x => {\n if (typeof imports[x] === 'undefined') {\n imports[x] = x;\n }\n });\n }\n });\n } catch (e) {\n console.error(e);\n throw e;\n }\n }),\n );\n\n if (include) {\n include.forEach(item => {\n if (typeof item === 'string') {\n imports[item] = item;\n } else {\n imports[item[0]] = item[1];\n }\n });\n }\n\n if (!('react' in imports)) {\n imports.react = 'react';\n }\n\n const importKeys = Object.keys(imports);\n const code = [\n ...importKeys.map(\n (x, index) => `import * as i_${index} from '${imports[x]}';`,\n ),\n 'const imports = new Map();',\n ...importKeys.map((x, index) => `imports.set('${x}', i_${index});`),\n 'function getImport(name, getDefault) {',\n ' if (!imports.has(name)) {',\n ' throw new Error(\"Module \" + name + \" not found\");',\n ' }',\n ' const result = imports.get(name);',\n ' if (getDefault && typeof result === \"object\") {',\n ' return result.default || result;',\n ' }',\n ' return result;',\n '}',\n 'export { imports };',\n 'export default getImport;',\n ].join('\\n');\n\n // console.log('playground-imports', code);\n\n playgroundVirtualModule.writeModule('_rspress_playground_imports', code);\n },\n builderConfig: {\n source: {\n define: {\n __PLAYGROUND_DIRECTION__: JSON.stringify(defaultDirection),\n __PLAYGROUND_MONACO_LOADER__: JSON.stringify(monacoLoader),\n __PLAYGROUND_MONACO_OPTIONS__: JSON.stringify(monacoOptions),\n },\n include: [join(__dirname, '..', '..', '..')],\n },\n html: {\n tags: [\n ...preloads.map(url => ({\n tag: 'link',\n head: true,\n attrs: {\n rel: 'preload',\n href: url,\n as: 'script',\n },\n })),\n {\n tag: 'script',\n head: true,\n attrs: {\n id: 'rspress-playground-babel',\n async: true,\n src: babelUrl || DEFAULT_BABEL_URL,\n },\n },\n ],\n },\n tools: {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment, @typescript-eslint/prefer-ts-expect-error\n // @ts-ignore\n rspack: {\n plugins: [playgroundVirtualModule],\n },\n },\n },\n markdown: {\n remarkPlugins: [\n [remarkPlugin, { getRouteMeta, editorPosition, defaultRenderMode }],\n ],\n globalComponents: [\n render\n ? render\n : path.join(staticPath, 'global-components', 'Playground.tsx'),\n ],\n },\n globalStyles: path.join(staticPath, 'global-styles', 'web.css'),\n };\n}\n","import path from 'path';\n\nexport const staticPath = path.join(__dirname, '../../../static');\n","/* eslint-disable consistent-return */\nimport type { Program } from '@babel/types';\nimport oxc from '@oxidation-compiler/napi';\n\nexport const parseImports = (code: string, sourceExt: string) => {\n const parsed = oxc.parseSync(code, {\n sourceType: 'module',\n sourceFilename: `index.${sourceExt}`,\n });\n\n const ast = JSON.parse(parsed.program) as Program;\n\n const result: string[] = [];\n\n // oxc didn't have \"traverse\", so it currently only scans the first level\n // (generally, demos are not too complicated, right?)\n ast.body.forEach(statement => {\n if (statement.type === 'ImportDeclaration') {\n result.push(statement.source.value);\n }\n });\n\n return result;\n};\n\nexport const getNodeAttribute = (\n node: any,\n attrName: string,\n): string | undefined => {\n return node.attributes.find(\n (attr: { name: string; value: string }) => attr.name === attrName,\n )?.value;\n};\n\nexport const getNodeMeta = (\n node: any,\n metaName: string,\n): string | undefined => {\n if (!node.meta) {\n return;\n }\n const meta: string[] = node.meta.split(' ');\n const item: string | undefined = meta.find((x: string) =>\n x.startsWith(metaName),\n );\n if (item?.startsWith(`${metaName}=`)) {\n return item.substring(metaName.length + 1);\n }\n return item;\n};\n","import { dirname, join, resolve } from 'path';\nimport { visit } from 'unist-util-visit';\nimport fs from '@rspress/shared/fs-extra';\nimport type { RouteMeta } from '@rspress/shared';\nimport type { Plugin } from 'unified';\nimport type { Root } from 'mdast';\nimport { getNodeAttribute, getNodeMeta } from './utils';\n\nfunction createPlaygroundNode(\n currentNode: any,\n attrs: Array<[string, string]>,\n) {\n Object.assign(currentNode, {\n type: 'mdxJsxFlowElement',\n name: 'Playground',\n attributes: attrs.map(it => ({\n type: 'mdxJsxAttribute',\n name: it[0],\n value: it[1],\n })),\n });\n}\n\ninterface RemarkPluginProps {\n getRouteMeta: () => RouteMeta[];\n editorPosition: 'left' | 'right';\n defaultRenderMode: 'pure' | 'playground';\n}\n\n/**\n * remark plugin to transform code to demo\n */\nexport const remarkPlugin: Plugin<[RemarkPluginProps], Root> = ({\n getRouteMeta,\n editorPosition,\n defaultRenderMode,\n}) => {\n const routeMeta = getRouteMeta();\n\n return (tree, vfile) => {\n const route = routeMeta.find(\n meta =>\n resolve(meta.absolutePath) === resolve(vfile.path || vfile.history[0]),\n );\n if (!route) {\n return;\n }\n\n // 1. External demo , use <code src=\"xxx\" /> to declare demo\n visit(tree, 'mdxJsxFlowElement', (node: any) => {\n if (node.name === 'code') {\n const src = getNodeAttribute(node, 'src');\n if (!src) {\n return;\n }\n const demoPath = join(dirname(route.absolutePath), src);\n if (!fs.existsSync(demoPath)) {\n return;\n }\n const direction = getNodeAttribute(node, 'direction') || '';\n const code = fs.readFileSync(demoPath, {\n encoding: 'utf8',\n });\n const language = src.substr(src.lastIndexOf('.') + 1);\n createPlaygroundNode(node, [\n ['code', code],\n ['language', language],\n ['direction', direction],\n ['editorPosition', editorPosition],\n ]);\n }\n });\n\n // 2. Internal demo, use ```j/tsx to declare demo\n visit(tree, 'code', node => {\n if (node.lang === 'jsx' || node.lang === 'tsx') {\n const hasPureMeta = node?.meta?.includes('pure');\n const hasPlaygroundMeta = node?.meta?.includes('playground');\n\n let noTransform;\n switch (defaultRenderMode) {\n case 'pure':\n noTransform = !hasPlaygroundMeta;\n break;\n case 'playground':\n noTransform = hasPureMeta;\n break;\n default:\n break;\n }\n\n // do not anything for pure mode\n if (noTransform) {\n return;\n }\n\n const direction = getNodeMeta(node, 'direction') || '';\n\n createPlaygroundNode(node, [\n ['code', node.value],\n ['language', node.lang],\n ['direction', direction],\n ['editorPosition', editorPosition],\n ]);\n }\n });\n };\n};\n","export const DEFAULT_BABEL_URL =\n 'https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.22.20/babel.min.js';\n\nexport const DEFAULT_MONACO_URL =\n 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.43.0/min/vs';\n","export function normalizeUrl(u: string) {\n return u.replace(/\\/\\//g, '/');\n}\n"]}
|
package/dist/web/cjs/index.js
CHANGED
|
@@ -134,23 +134,27 @@ function createVariableDeclaration(id, init) {
|
|
|
134
134
|
kind: "const"
|
|
135
135
|
};
|
|
136
136
|
}
|
|
137
|
+
function createIdentifier(name) {
|
|
138
|
+
return {
|
|
139
|
+
type: "Identifier",
|
|
140
|
+
name
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
function createObjectProperty(key, value) {
|
|
144
|
+
return {
|
|
145
|
+
type: "ObjectProperty",
|
|
146
|
+
key: createIdentifier(key),
|
|
147
|
+
computed: false,
|
|
148
|
+
shorthand: key === value,
|
|
149
|
+
value: createIdentifier(value)
|
|
150
|
+
};
|
|
151
|
+
}
|
|
137
152
|
function createObjectPattern(names) {
|
|
138
153
|
return {
|
|
139
154
|
type: "ObjectPattern",
|
|
140
|
-
properties: names.map(
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
type: "Identifier",
|
|
144
|
-
name
|
|
145
|
-
},
|
|
146
|
-
computed: false,
|
|
147
|
-
method: false,
|
|
148
|
-
shorthand: true,
|
|
149
|
-
value: {
|
|
150
|
-
type: "Identifier",
|
|
151
|
-
name
|
|
152
|
-
}
|
|
153
|
-
}))
|
|
155
|
+
properties: names.map(
|
|
156
|
+
(name) => Array.isArray(name) ? createObjectProperty(name[0], name[1]) : createObjectProperty(name, name)
|
|
157
|
+
)
|
|
154
158
|
};
|
|
155
159
|
}
|
|
156
160
|
function createGetImport(name, getDefault) {
|
|
@@ -270,7 +274,14 @@ var Runner = class extends import_react3.Component {
|
|
|
270
274
|
);
|
|
271
275
|
}
|
|
272
276
|
if (specifier.type === "ImportSpecifier") {
|
|
273
|
-
|
|
277
|
+
if ("name" in specifier.imported && specifier.imported.name !== specifier.local.name) {
|
|
278
|
+
specifiers.push([
|
|
279
|
+
specifier.imported.name,
|
|
280
|
+
specifier.local.name
|
|
281
|
+
]);
|
|
282
|
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web/editor.tsx","../../../src/web/constant.ts","../../../src/web/runner.tsx","../../../src/web/ast.ts","../../../src/web/babel.ts"],"sourcesContent":["export {\n default as MonacoEditor,\n loader as MonacoEditorLoader,\n EditorProps as MonacoEditorProps,\n} from '@monaco-editor/react';\nexport { Editor } from './editor';\nexport { Runner } from './runner';\n","import React, { useMemo } from 'react';\nimport MonacoEditor, {\n loader,\n EditorProps as MonacoEditorProps,\n} from '@monaco-editor/react';\nimport { useDark } from '@rspress/core/runtime';\nimport { DEFAULT_MONACO_URL } from './constant';\n\n// inject by Rsbuild in cli/index.ts\n// see: https://rsbuild.dev/zh/config/options/source.html#sourcedefine\ndeclare global {\n const __PLAYGROUND_MONACO_LOADER__: any;\n const __PLAYGROUND_MONACO_OPTIONS__: any;\n}\n\nfunction initLoader() {\n let loaderConfig = {\n paths: {\n vs: DEFAULT_MONACO_URL,\n },\n };\n\n try {\n const keys = Object.keys(__PLAYGROUND_MONACO_LOADER__);\n\n if (keys.length > 0) {\n loaderConfig = __PLAYGROUND_MONACO_LOADER__;\n }\n } catch (e) {\n // ignore\n }\n\n loader.config(loaderConfig);\n}\ninitLoader();\n\nfunction getMonacoOptions() {\n try {\n return __PLAYGROUND_MONACO_OPTIONS__;\n } catch (e) {\n // ignore\n }\n return {};\n}\n\nexport type EditorProps = Partial<MonacoEditorProps>;\n\nexport function Editor(props: EditorProps) {\n const { options, className = '', theme: themeProp, ...rest } = props || {};\n\n const dark = useDark();\n const theme = useMemo(() => {\n if (themeProp) {\n return themeProp;\n }\n return dark ? 'vs-dark' : 'light';\n }, [themeProp, dark]);\n\n return (\n <div className={`rspress-playground-editor ${className}`}>\n <MonacoEditor\n {...rest}\n theme={theme}\n options={{\n minimap: {\n enabled: true,\n autohide: true,\n },\n fontSize: 14,\n lineNumbersMinChars: 7,\n scrollBeyondLastLine: false,\n automaticLayout: true,\n wordBasedSuggestions: true,\n quickSuggestions: true,\n scrollbar: {\n verticalScrollbarSize: 8,\n horizontalScrollbarSize: 8,\n },\n scrollPredominantAxis: false,\n ...getMonacoOptions(),\n ...options,\n }}\n />\n </div>\n );\n}\n","export const DEFAULT_BABEL_URL =\n 'https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.22.20/babel.min.js';\n\nexport const DEFAULT_MONACO_URL =\n 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.43.0/min/vs';\n","import type { Node } from '@babel/types';\nimport React, { Component, HTMLAttributes } from 'react';\nimport {\n createGetImport,\n createObjectPattern,\n createVariableDeclaration,\n} from './ast';\nimport { getBabel } from './babel';\n\ninterface RunnerProps extends HTMLAttributes<HTMLDivElement> {\n code: string;\n language: string;\n getImport: (name: string, getDefault?: boolean) => void;\n}\n\ninterface RunnerState {\n error?: Error;\n comp: any;\n}\n\nconst DEBOUNCE_TIME = 800;\n\nclass Runner extends Component<RunnerProps, RunnerState> {\n static getDerivedStateFromError(error: Error) {\n return {\n error,\n comp: null,\n };\n }\n\n timer: any;\n\n constructor(props: RunnerProps) {\n super(props);\n\n this.state = {\n error: undefined,\n comp: null,\n };\n\n this.doCompile = this.doCompile.bind(this);\n this.waitCompile = this.waitCompile.bind(this);\n }\n\n waitCompile(targetCode: string) {\n if (this.timer) {\n clearTimeout(this.timer);\n }\n this.timer = setTimeout(() => {\n this.timer = null;\n this.doCompile(targetCode);\n }, DEBOUNCE_TIME);\n }\n\n async doCompile(targetCode: string) {\n const { language, getImport } = this.props;\n const babel = await getBabel();\n try {\n const presets = [\n [babel.availablePresets.react],\n [babel.availablePresets.env, { modules: 'commonjs' }],\n ];\n if (language === 'tsx' || language === 'ts') {\n presets.unshift([\n babel.availablePresets.typescript,\n {\n allExtensions: true,\n isTSX: language === 'tsx',\n },\n ]);\n }\n const result = babel.transform(targetCode, {\n sourceType: 'module',\n sourceMaps: 'inline',\n presets,\n plugins: [\n {\n pre() {\n this.hasReactImported = false;\n },\n visitor: {\n ImportDeclaration(path) {\n const pkg = path.node.source.value;\n const code: Node[] = [];\n const specifiers: string[] = [];\n for (const specifier of path.node.specifiers) {\n if (specifier.local.name === 'React') {\n this.hasReactImported = true;\n }\n // import X from 'xxx'\n if (specifier.type === 'ImportDefaultSpecifier') {\n // const ${specifier.local.name} = __get_import()\n code.push(\n createVariableDeclaration(\n specifier.local.name,\n createGetImport(pkg, true),\n ),\n );\n }\n // import * as X from 'xxx'\n if (specifier.type === 'ImportNamespaceSpecifier') {\n // const ${specifier.local.name} = __get_import()\n code.push(\n createVariableDeclaration(\n specifier.local.name,\n createGetImport(pkg),\n ),\n );\n }\n // import { a, b, c } from 'xxx'\n if (specifier.type === 'ImportSpecifier') {\n // const {${specifier.local.name}} = __get_import()\n specifiers.push(specifier.local.name);\n }\n }\n if (specifiers.length > 0) {\n code.push(\n createVariableDeclaration(\n createObjectPattern(specifiers),\n createGetImport(pkg),\n ),\n );\n }\n path.replaceWithMultiple(code);\n },\n },\n post(file) {\n // Auto import React\n if (!this.hasReactImported) {\n file.ast.program.body.unshift(\n createVariableDeclaration(\n 'React',\n createGetImport('react', true),\n ),\n );\n }\n },\n },\n ],\n });\n\n // Code has been updated\n if (targetCode !== this.props.code || !result || !result.code) {\n return;\n }\n\n const runExports: any = {};\n // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func\n const func = new Function('__get_import', 'exports', result.code);\n func(getImport, runExports);\n\n if (runExports.default) {\n this.setState({\n error: undefined,\n comp: React.createElement(runExports.default),\n });\n return;\n }\n\n this.setState({\n error: new Error('No default export'),\n });\n } catch (e) {\n // Code has been updated\n if (targetCode !== this.props.code) {\n return;\n }\n console.error(e);\n this.setState({\n error: e as Error,\n });\n }\n }\n\n componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {\n console.error(error);\n console.error(errorInfo);\n }\n\n componentDidMount() {\n this.doCompile(this.props.code);\n }\n\n componentDidUpdate(prevProps: RunnerProps) {\n if (prevProps.code !== this.props.code) {\n this.waitCompile(this.props.code);\n }\n }\n\n render() {\n const { className = '', code, language, getImport, ...rest } = this.props;\n const { error, comp } = this.state;\n\n return (\n <div className={`rspress-playground-runner ${className}`} {...rest}>\n {comp}\n {error && (\n <pre className=\"rspress-playground-error\">{error.message}</pre>\n )}\n </div>\n );\n }\n}\n\nexport { Runner };\n","import type {\n CallExpression,\n Expression,\n ObjectPattern,\n VariableDeclaration,\n} from '@babel/types';\n\nexport function createVariableDeclaration(\n id: string | ObjectPattern,\n init: Expression,\n): VariableDeclaration {\n return {\n type: 'VariableDeclaration',\n declarations: [\n {\n type: 'VariableDeclarator',\n id:\n typeof id === 'string'\n ? {\n type: 'Identifier',\n name: id,\n }\n : id,\n init,\n },\n ],\n kind: 'const',\n };\n}\n\nexport function createObjectPattern(names: string[]): ObjectPattern {\n return {\n type: 'ObjectPattern',\n properties: names.map(name => ({\n type: 'ObjectProperty',\n key: {\n type: 'Identifier',\n name,\n },\n computed: false,\n method: false,\n shorthand: true,\n value: {\n type: 'Identifier',\n name,\n },\n })),\n };\n}\n\nexport function createGetImport(\n name: string,\n getDefault?: boolean,\n): CallExpression {\n return {\n type: 'CallExpression',\n callee: {\n type: 'Identifier',\n name: '__get_import',\n },\n arguments: [\n {\n type: 'StringLiteral',\n value: name,\n },\n {\n type: 'BooleanLiteral',\n value: Boolean(getDefault),\n },\n ],\n };\n}\n","import type babel from '@babel/standalone';\n\ntype Babel = typeof babel;\n\ndeclare global {\n interface Window {\n Babel: Babel;\n }\n}\n\nfunction getBabel(): Babel | Promise<Babel> {\n if (window.Babel) {\n return window.Babel;\n }\n const el = document.getElementById('rspress-playground-babel');\n if (!el) {\n throw new Error('Babel not found');\n }\n return new Promise(resolve => {\n el.addEventListener('load', () => {\n resolve(window.Babel);\n });\n });\n}\n\nexport { getBabel };\n"]}
|
|
1
|
+
{"version":3,"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,gBAIO;;;ACJP,mBAA+B;AAC/B,IAAAA,gBAGO;AACP,qB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import_jsx_runtime","React"],"sources":["../../../src/web/index.ts","../../../src/web/editor.tsx","../../../src/web/constant.ts","../../../src/web/runner.tsx","../../../src/web/ast.ts","../../../src/web/babel.ts"],"sourcesContent":["export {\n default as MonacoEditor,\n loader as MonacoEditorLoader,\n EditorProps as MonacoEditorProps,\n} from '@monaco-editor/react';\nexport { Editor } from './editor';\nexport { Runner } from './runner';\n","import React, { useMemo } from 'react';\nimport MonacoEditor, {\n loader,\n EditorProps as MonacoEditorProps,\n} from '@monaco-editor/react';\nimport { useDark } from '@rspress/core/runtime';\nimport { DEFAULT_MONACO_URL } from './constant';\n\n// inject by Rsbuild in cli/index.ts\n// see: https://rsbuild.dev/zh/config/options/source.html#sourcedefine\ndeclare global {\n const __PLAYGROUND_MONACO_LOADER__: any;\n const __PLAYGROUND_MONACO_OPTIONS__: any;\n}\n\nfunction initLoader() {\n let loaderConfig = {\n paths: {\n vs: DEFAULT_MONACO_URL,\n },\n };\n\n try {\n const keys = Object.keys(__PLAYGROUND_MONACO_LOADER__);\n\n if (keys.length > 0) {\n loaderConfig = __PLAYGROUND_MONACO_LOADER__;\n }\n } catch (e) {\n // ignore\n }\n\n loader.config(loaderConfig);\n}\ninitLoader();\n\nfunction getMonacoOptions() {\n try {\n return __PLAYGROUND_MONACO_OPTIONS__;\n } catch (e) {\n // ignore\n }\n return {};\n}\n\nexport type EditorProps = Partial<MonacoEditorProps>;\n\nexport function Editor(props: EditorProps) {\n const { options, className = '', theme: themeProp, ...rest } = props || {};\n\n const dark = useDark();\n const theme = useMemo(() => {\n if (themeProp) {\n return themeProp;\n }\n return dark ? 'vs-dark' : 'light';\n }, [themeProp, dark]);\n\n return (\n <div className={`rspress-playground-editor ${className}`}>\n <MonacoEditor\n {...rest}\n theme={theme}\n options={{\n minimap: {\n enabled: true,\n autohide: true,\n },\n fontSize: 14,\n lineNumbersMinChars: 7,\n scrollBeyondLastLine: false,\n automaticLayout: true,\n wordBasedSuggestions: true,\n quickSuggestions: true,\n scrollbar: {\n verticalScrollbarSize: 8,\n horizontalScrollbarSize: 8,\n },\n scrollPredominantAxis: false,\n ...getMonacoOptions(),\n ...options,\n }}\n />\n </div>\n );\n}\n","export const DEFAULT_BABEL_URL =\n 'https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.22.20/babel.min.js';\n\nexport const DEFAULT_MONACO_URL =\n 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.43.0/min/vs';\n","import type { Node } from '@babel/types';\nimport React, { Component, HTMLAttributes } from 'react';\nimport {\n createGetImport,\n createObjectPattern,\n createVariableDeclaration,\n} from './ast';\nimport { getBabel } from './babel';\n\ninterface RunnerProps extends HTMLAttributes<HTMLDivElement> {\n code: string;\n language: string;\n getImport: (name: string, getDefault?: boolean) => void;\n}\n\ninterface RunnerState {\n error?: Error;\n comp: any;\n}\n\nconst DEBOUNCE_TIME = 800;\n\nclass Runner extends Component<RunnerProps, RunnerState> {\n static getDerivedStateFromError(error: Error) {\n return {\n error,\n comp: null,\n };\n }\n\n timer: any;\n\n constructor(props: RunnerProps) {\n super(props);\n\n this.state = {\n error: undefined,\n comp: null,\n };\n\n this.doCompile = this.doCompile.bind(this);\n this.waitCompile = this.waitCompile.bind(this);\n }\n\n waitCompile(targetCode: string) {\n if (this.timer) {\n clearTimeout(this.timer);\n }\n this.timer = setTimeout(() => {\n this.timer = null;\n this.doCompile(targetCode);\n }, DEBOUNCE_TIME);\n }\n\n async doCompile(targetCode: string) {\n const { language, getImport } = this.props;\n const babel = await getBabel();\n try {\n const presets = [\n [babel.availablePresets.react],\n [babel.availablePresets.env, { modules: 'commonjs' }],\n ];\n if (language === 'tsx' || language === 'ts') {\n presets.unshift([\n babel.availablePresets.typescript,\n {\n allExtensions: true,\n isTSX: language === 'tsx',\n },\n ]);\n }\n const result = babel.transform(targetCode, {\n sourceType: 'module',\n sourceMaps: 'inline',\n presets,\n plugins: [\n {\n pre() {\n this.hasReactImported = false;\n },\n visitor: {\n ImportDeclaration(path) {\n const pkg = path.node.source.value;\n const code: Node[] = [];\n const specifiers: (string | [string, string])[] = [];\n for (const specifier of path.node.specifiers) {\n if (specifier.local.name === 'React') {\n this.hasReactImported = true;\n }\n // import X from 'xxx'\n if (specifier.type === 'ImportDefaultSpecifier') {\n // const ${specifier.local.name} = __get_import()\n code.push(\n createVariableDeclaration(\n specifier.local.name,\n createGetImport(pkg, true),\n ),\n );\n }\n // import * as X from 'xxx'\n if (specifier.type === 'ImportNamespaceSpecifier') {\n // const ${specifier.local.name} = __get_import()\n code.push(\n createVariableDeclaration(\n specifier.local.name,\n createGetImport(pkg),\n ),\n );\n }\n // import { a, b, c } from 'xxx'\n if (specifier.type === 'ImportSpecifier') {\n if (\n 'name' in specifier.imported &&\n specifier.imported.name !== specifier.local.name\n ) {\n // const {${specifier.imported.name}: ${specifier.local.name}} = __get_import()\n specifiers.push([\n specifier.imported.name,\n specifier.local.name,\n ]);\n } else {\n // const {${specifier.local.name}} = __get_import()\n specifiers.push(specifier.local.name);\n }\n }\n }\n if (specifiers.length > 0) {\n code.push(\n createVariableDeclaration(\n createObjectPattern(specifiers),\n createGetImport(pkg),\n ),\n );\n }\n path.replaceWithMultiple(code);\n },\n },\n post(file) {\n // Auto import React\n if (!this.hasReactImported) {\n file.ast.program.body.unshift(\n createVariableDeclaration(\n 'React',\n createGetImport('react', true),\n ),\n );\n }\n },\n },\n ],\n });\n\n // Code has been updated\n if (targetCode !== this.props.code || !result || !result.code) {\n return;\n }\n\n const runExports: any = {};\n // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func\n const func = new Function('__get_import', 'exports', result.code);\n func(getImport, runExports);\n\n if (runExports.default) {\n this.setState({\n error: undefined,\n comp: React.createElement(runExports.default),\n });\n return;\n }\n\n this.setState({\n error: new Error('No default export'),\n });\n } catch (e) {\n // Code has been updated\n if (targetCode !== this.props.code) {\n return;\n }\n console.error(e);\n this.setState({\n error: e as Error,\n });\n }\n }\n\n componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {\n console.error(error);\n console.error(errorInfo);\n }\n\n componentDidMount() {\n this.doCompile(this.props.code);\n }\n\n componentDidUpdate(prevProps: RunnerProps) {\n if (prevProps.code !== this.props.code) {\n this.waitCompile(this.props.code);\n }\n }\n\n render() {\n const { className = '', code, language, getImport, ...rest } = this.props;\n const { error, comp } = this.state;\n\n return (\n <div className={`rspress-playground-runner ${className}`} {...rest}>\n {comp}\n {error && (\n <pre className=\"rspress-playground-error\">{error.message}</pre>\n )}\n </div>\n );\n }\n}\n\nexport { Runner };\n","import type {\n CallExpression,\n Expression,\n Identifier,\n ObjectPattern,\n ObjectProperty,\n VariableDeclaration,\n} from '@babel/types';\n\nexport function createVariableDeclaration(\n id: string | ObjectPattern,\n init: Expression,\n): VariableDeclaration {\n return {\n type: 'VariableDeclaration',\n declarations: [\n {\n type: 'VariableDeclarator',\n id:\n typeof id === 'string'\n ? {\n type: 'Identifier',\n name: id,\n }\n : id,\n init,\n },\n ],\n kind: 'const',\n };\n}\n\nfunction createIdentifier(name: string): Identifier {\n return {\n type: 'Identifier',\n name,\n };\n}\n\nfunction createObjectProperty(key: string, value: string): ObjectProperty {\n return {\n type: 'ObjectProperty',\n key: createIdentifier(key),\n computed: false,\n shorthand: key === value,\n value: createIdentifier(value),\n };\n}\n\nexport function createObjectPattern(\n names: (string | [string, string])[],\n): ObjectPattern {\n return {\n type: 'ObjectPattern',\n properties: names.map(name =>\n Array.isArray(name)\n ? createObjectProperty(name[0], name[1])\n : createObjectProperty(name, name),\n ),\n };\n}\n\nexport function createGetImport(\n name: string,\n getDefault?: boolean,\n): CallExpression {\n return {\n type: 'CallExpression',\n callee: {\n type: 'Identifier',\n name: '__get_import',\n },\n arguments: [\n {\n type: 'StringLiteral',\n value: name,\n },\n {\n type: 'BooleanLiteral',\n value: Boolean(getDefault),\n },\n ],\n };\n}\n","import type babel from '@babel/standalone';\n\ntype Babel = typeof babel;\n\ndeclare global {\n interface Window {\n Babel: Babel;\n }\n}\n\nfunction getBabel(): Babel | Promise<Babel> {\n if (window.Babel) {\n return window.Babel;\n }\n const el = document.getElementById('rspress-playground-babel');\n if (!el) {\n throw new Error('Babel not found');\n }\n return new Promise(resolve => {\n el.addEventListener('load', () => {\n resolve(window.Babel);\n });\n });\n}\n\nexport { getBabel };\n"]}
|
package/dist/web/esm/index.js
CHANGED
|
@@ -104,23 +104,27 @@ function createVariableDeclaration(id, init) {
|
|
|
104
104
|
kind: "const"
|
|
105
105
|
};
|
|
106
106
|
}
|
|
107
|
+
function createIdentifier(name) {
|
|
108
|
+
return {
|
|
109
|
+
type: "Identifier",
|
|
110
|
+
name
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
function createObjectProperty(key, value) {
|
|
114
|
+
return {
|
|
115
|
+
type: "ObjectProperty",
|
|
116
|
+
key: createIdentifier(key),
|
|
117
|
+
computed: false,
|
|
118
|
+
shorthand: key === value,
|
|
119
|
+
value: createIdentifier(value)
|
|
120
|
+
};
|
|
121
|
+
}
|
|
107
122
|
function createObjectPattern(names) {
|
|
108
123
|
return {
|
|
109
124
|
type: "ObjectPattern",
|
|
110
|
-
properties: names.map(
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
type: "Identifier",
|
|
114
|
-
name
|
|
115
|
-
},
|
|
116
|
-
computed: false,
|
|
117
|
-
method: false,
|
|
118
|
-
shorthand: true,
|
|
119
|
-
value: {
|
|
120
|
-
type: "Identifier",
|
|
121
|
-
name
|
|
122
|
-
}
|
|
123
|
-
}))
|
|
125
|
+
properties: names.map(
|
|
126
|
+
(name) => Array.isArray(name) ? createObjectProperty(name[0], name[1]) : createObjectProperty(name, name)
|
|
127
|
+
)
|
|
124
128
|
};
|
|
125
129
|
}
|
|
126
130
|
function createGetImport(name, getDefault) {
|
|
@@ -240,7 +244,14 @@ var Runner = class extends Component {
|
|
|
240
244
|
);
|
|
241
245
|
}
|
|
242
246
|
if (specifier.type === "ImportSpecifier") {
|
|
243
|
-
|
|
247
|
+
if ("name" in specifier.imported && specifier.imported.name !== specifier.local.name) {
|
|
248
|
+
specifiers.push([
|
|
249
|
+
specifier.imported.name,
|
|
250
|
+
specifier.local.name
|
|
251
|
+
]);
|
|
252
|
+
} else {
|
|
253
|
+
specifiers.push(specifier.local.name);
|
|
254
|
+
}
|
|
244
255
|
}
|
|
245
256
|
}
|
|
246
257
|
if (specifiers.length > 0) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"mappings":";;;;;;;;AAAA;AAAA,EACa,WAAXA;AAAA,EACU,UAAVC;AAAA,EACe;AAAA,OACV;;;ACJP,SAAgB,eAAe;AAC/B,OAAO;AAAA,EACL;AAAA,OAEK;AACP,SAAS,eAAe;;;ACFjB,IAAM,qBACX;;;ADwDI;AA7CN,SAAS,aAAa;AACpB,MAAI,eAAe;AAAA,IACjB,OAAO;AAAA,MACL,IAAI;AAAA,IACN;AAAA,EACF;AAEA,MAAI;AACF,UAAM,OAAO,OAAO,KAAK,4BAA4B;AAErD,QAAI,KAAK,SAAS,GAAG;AACnB,qBAAe;AAAA,IACjB;AAAA,EACF,SAAS,GAAG;AAAA,EAEZ;AAEA,SAAO,OAAO,YAAY;AAC5B;AACA,WAAW;AAEX,SAAS,mBAAmB;AAC1B,MAAI;AACF,WAAO;AAAA,EACT,SAAS,GAAG;AAAA,EAEZ;AACA,SAAO,CAAC;AACV;AAIO,SAAS,OAAO,OAAoB;AACzC,QAAM,EAAE,SAAS,YAAY,IAAI,OAAO,WAAW,GAAG,KAAK,IAAI,SAAS,CAAC;AAEzE,QAAM,OAAO,QAAQ;AACrB,QAAM,QAAQ,QAAQ,MAAM;AAC1B,QAAI,WAAW;AACb,aAAO;AAAA,IACT;AACA,WAAO,OAAO,YAAY;AAAA,EAC5B,GAAG,CAAC,WAAW,IAAI,CAAC;AAEpB,SACE,oBAAC,SAAI,WAAW,6BAA6B,SAAS,IACpD;AAAA,IAAC;AAAA;AAAA,MACE,GAAG;AAAA,MACJ;AAAA,MACA,SAAS;AAAA,QACP,SAAS;AAAA,UACP,S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E7D;AAAA,EAEJ;AACF","names":["default","loader","React","jsx"],"sources":["../../../src/web/index.ts","../../../src/web/editor.tsx","../../../src/web/constant.ts","../../../src/web/runner.tsx","../../../src/web/ast.ts","../../../src/web/babel.ts"],"sourcesContent":["export {\n default as MonacoEditor,\n loader as MonacoEditorLoader,\n EditorProps as MonacoEditorProps,\n} from '@monaco-editor/react';\nexport { Editor } from './editor';\nexport { Runner } from './runner';\n","import React, { useMemo } from 'react';\nimport MonacoEditor, {\n loader,\n EditorProps as MonacoEditorProps,\n} from '@monaco-editor/react';\nimport { useDark } from '@rspress/core/runtime';\nimport { DEFAULT_MONACO_URL } from './constant';\n\n// inject by Rsbuild in cli/index.ts\n// see: https://rsbuild.dev/zh/config/options/source.html#sourcedefine\ndeclare global {\n const __PLAYGROUND_MONACO_LOADER__: any;\n const __PLAYGROUND_MONACO_OPTIONS__: any;\n}\n\nfunction initLoader() {\n let loaderConfig = {\n paths: {\n vs: DEFAULT_MONACO_URL,\n },\n };\n\n try {\n const keys = Object.keys(__PLAYGROUND_MONACO_LOADER__);\n\n if (keys.length > 0) {\n loaderConfig = __PLAYGROUND_MONACO_LOADER__;\n }\n } catch (e) {\n // ignore\n }\n\n loader.config(loaderConfig);\n}\ninitLoader();\n\nfunction getMonacoOptions() {\n try {\n return __PLAYGROUND_MONACO_OPTIONS__;\n } catch (e) {\n // ignore\n }\n return {};\n}\n\nexport type EditorProps = Partial<MonacoEditorProps>;\n\nexport function Editor(props: EditorProps) {\n const { options, className = '', theme: themeProp, ...rest } = props || {};\n\n const dark = useDark();\n const theme = useMemo(() => {\n if (themeProp) {\n return themeProp;\n }\n return dark ? 'vs-dark' : 'light';\n }, [themeProp, dark]);\n\n return (\n <div className={`rspress-playground-editor ${className}`}>\n <MonacoEditor\n {...rest}\n theme={theme}\n options={{\n minimap: {\n enabled: true,\n autohide: true,\n },\n fontSize: 14,\n lineNumbersMinChars: 7,\n scrollBeyondLastLine: false,\n automaticLayout: true,\n wordBasedSuggestions: true,\n quickSuggestions: true,\n scrollbar: {\n verticalScrollbarSize: 8,\n horizontalScrollbarSize: 8,\n },\n scrollPredominantAxis: false,\n ...getMonacoOptions(),\n ...options,\n }}\n />\n </div>\n );\n}\n","export const DEFAULT_BABEL_URL =\n 'https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.22.20/babel.min.js';\n\nexport const DEFAULT_MONACO_URL =\n 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.43.0/min/vs';\n","import type { Node } from '@babel/types';\nimport React, { Component, HTMLAttributes } from 'react';\nimport {\n createGetImport,\n createObjectPattern,\n createVariableDeclaration,\n} from './ast';\nimport { getBabel } from './babel';\n\ninterface RunnerProps extends HTMLAttributes<HTMLDivElement> {\n code: string;\n language: string;\n getImport: (name: string, getDefault?: boolean) => void;\n}\n\ninterface RunnerState {\n error?: Error;\n comp: any;\n}\n\nconst DEBOUNCE_TIME = 800;\n\nclass Runner extends Component<RunnerProps, RunnerState> {\n static getDerivedStateFromError(error: Error) {\n return {\n error,\n comp: null,\n };\n }\n\n timer: any;\n\n constructor(props: RunnerProps) {\n super(props);\n\n this.state = {\n error: undefined,\n comp: null,\n };\n\n this.doCompile = this.doCompile.bind(this);\n this.waitCompile = this.waitCompile.bind(this);\n }\n\n waitCompile(targetCode: string) {\n if (this.timer) {\n clearTimeout(this.timer);\n }\n this.timer = setTimeout(() => {\n this.timer = null;\n this.doCompile(targetCode);\n }, DEBOUNCE_TIME);\n }\n\n async doCompile(targetCode: string) {\n const { language, getImport } = this.props;\n const babel = await getBabel();\n try {\n const presets = [\n [babel.availablePresets.react],\n [babel.availablePresets.env, { modules: 'commonjs' }],\n ];\n if (language === 'tsx' || language === 'ts') {\n presets.unshift([\n babel.availablePresets.typescript,\n {\n allExtensions: true,\n isTSX: language === 'tsx',\n },\n ]);\n }\n const result = babel.transform(targetCode, {\n sourceType: 'module',\n sourceMaps: 'inline',\n presets,\n plugins: [\n {\n pre() {\n this.hasReactImported = false;\n },\n visitor: {\n ImportDeclaration(path) {\n const pkg = path.node.source.value;\n const code: Node[] = [];\n const specifiers: string[] = [];\n for (const specifier of path.node.specifiers) {\n if (specifier.local.name === 'React') {\n this.hasReactImported = true;\n }\n // import X from 'xxx'\n if (specifier.type === 'ImportDefaultSpecifier') {\n // const ${specifier.local.name} = __get_import()\n code.push(\n createVariableDeclaration(\n specifier.local.name,\n createGetImport(pkg, true),\n ),\n );\n }\n // import * as X from 'xxx'\n if (specifier.type === 'ImportNamespaceSpecifier') {\n // const ${specifier.local.name} = __get_import()\n code.push(\n createVariableDeclaration(\n specifier.local.name,\n createGetImport(pkg),\n ),\n );\n }\n // import { a, b, c } from 'xxx'\n if (specifier.type === 'ImportSpecifier') {\n // const {${specifier.local.name}} = __get_import()\n specifiers.push(specifier.local.name);\n }\n }\n if (specifiers.length > 0) {\n code.push(\n createVariableDeclaration(\n createObjectPattern(specifiers),\n createGetImport(pkg),\n ),\n );\n }\n path.replaceWithMultiple(code);\n },\n },\n post(file) {\n // Auto import React\n if (!this.hasReactImported) {\n file.ast.program.body.unshift(\n createVariableDeclaration(\n 'React',\n createGetImport('react', true),\n ),\n );\n }\n },\n },\n ],\n });\n\n // Code has been updated\n if (targetCode !== this.props.code || !result || !result.code) {\n return;\n }\n\n const runExports: any = {};\n // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func\n const func = new Function('__get_import', 'exports', result.code);\n func(getImport, runExports);\n\n if (runExports.default) {\n this.setState({\n error: undefined,\n comp: React.createElement(runExports.default),\n });\n return;\n }\n\n this.setState({\n error: new Error('No default export'),\n });\n } catch (e) {\n // Code has been updated\n if (targetCode !== this.props.code) {\n return;\n }\n console.error(e);\n this.setState({\n error: e as Error,\n });\n }\n }\n\n componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {\n console.error(error);\n console.error(errorInfo);\n }\n\n componentDidMount() {\n this.doCompile(this.props.code);\n }\n\n componentDidUpdate(prevProps: RunnerProps) {\n if (prevProps.code !== this.props.code) {\n this.waitCompile(this.props.code);\n }\n }\n\n render() {\n const { className = '', code, language, getImport, ...rest } = this.props;\n const { error, comp } = this.state;\n\n return (\n <div className={`rspress-playground-runner ${className}`} {...rest}>\n {comp}\n {error && (\n <pre className=\"rspress-playground-error\">{error.message}</pre>\n )}\n </div>\n );\n }\n}\n\nexport { Runner };\n","import type {\n CallExpression,\n Expression,\n ObjectPattern,\n VariableDeclaration,\n} from '@babel/types';\n\nexport function createVariableDeclaration(\n id: string | ObjectPattern,\n init: Expression,\n): VariableDeclaration {\n return {\n type: 'VariableDeclaration',\n declarations: [\n {\n type: 'VariableDeclarator',\n id:\n typeof id === 'string'\n ? {\n type: 'Identifier',\n name: id,\n }\n : id,\n init,\n },\n ],\n kind: 'const',\n };\n}\n\nexport function createObjectPattern(names: string[]): ObjectPattern {\n return {\n type: 'ObjectPattern',\n properties: names.map(name => ({\n type: 'ObjectProperty',\n key: {\n type: 'Identifier',\n name,\n },\n computed: false,\n method: false,\n shorthand: true,\n value: {\n type: 'Identifier',\n name,\n },\n })),\n };\n}\n\nexport function createGetImport(\n name: string,\n getDefault?: boolean,\n): CallExpression {\n return {\n type: 'CallExpression',\n callee: {\n type: 'Identifier',\n name: '__get_import',\n },\n arguments: [\n {\n type: 'StringLiteral',\n value: name,\n },\n {\n type: 'BooleanLiteral',\n value: Boolean(getDefault),\n },\n ],\n };\n}\n","import type babel from '@babel/standalone';\n\ntype Babel = typeof babel;\n\ndeclare global {\n interface Window {\n Babel: Babel;\n }\n}\n\nfunction getBabel(): Babel | Promise<Babel> {\n if (window.Babel) {\n return window.Babel;\n }\n const el = document.getElementById('rspress-playground-babel');\n if (!el) {\n throw new Error('Babel not found');\n }\n return new Promise(resolve => {\n el.addEventListener('load', () => {\n resolve(window.Babel);\n });\n });\n}\n\nexport { getBabel };\n"]}
|
|
1
|
+
{"version":3,"mappings":";;;;;;;;AAAA;AAAA,EACa,WAAXA;AAAA,EACU,UAAVC;AAAA,EACe;AAAA,OACV;;;ACJP,SAAgB,eAAe;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AAA,OAE7D;AAAA,EAEJ;AACF","names":["default","loader","React","jsx"],"sources":["../../../src/web/index.ts","../../../src/web/editor.tsx","../../../src/web/constant.ts","../../../src/web/runner.tsx","../../../src/web/ast.ts","../../../src/web/babel.ts"],"sourcesContent":["export {\n default as MonacoEditor,\n loader as MonacoEditorLoader,\n EditorProps as MonacoEditorProps,\n} from '@monaco-editor/react';\nexport { Editor } from './editor';\nexport { Runner } from './runner';\n","import React, { useMemo } from 'react';\nimport MonacoEditor, {\n loader,\n EditorProps as MonacoEditorProps,\n} from '@monaco-editor/react';\nimport { useDark } from '@rspress/core/runtime';\nimport { DEFAULT_MONACO_URL } from './constant';\n\n// inject by Rsbuild in cli/index.ts\n// see: https://rsbuild.dev/zh/config/options/source.html#sourcedefine\ndeclare global {\n const __PLAYGROUND_MONACO_LOADER__: any;\n const __PLAYGROUND_MONACO_OPTIONS__: any;\n}\n\nfunction initLoader() {\n let loaderConfig = {\n paths: {\n vs: DEFAULT_MONACO_URL,\n },\n };\n\n try {\n const keys = Object.keys(__PLAYGROUND_MONACO_LOADER__);\n\n if (keys.length > 0) {\n loaderConfig = __PLAYGROUND_MONACO_LOADER__;\n }\n } catch (e) {\n // ignore\n }\n\n loader.config(loaderConfig);\n}\ninitLoader();\n\nfunction getMonacoOptions() {\n try {\n return __PLAYGROUND_MONACO_OPTIONS__;\n } catch (e) {\n // ignore\n }\n return {};\n}\n\nexport type EditorProps = Partial<MonacoEditorProps>;\n\nexport function Editor(props: EditorProps) {\n const { options, className = '', theme: themeProp, ...rest } = props || {};\n\n const dark = useDark();\n const theme = useMemo(() => {\n if (themeProp) {\n return themeProp;\n }\n return dark ? 'vs-dark' : 'light';\n }, [themeProp, dark]);\n\n return (\n <div className={`rspress-playground-editor ${className}`}>\n <MonacoEditor\n {...rest}\n theme={theme}\n options={{\n minimap: {\n enabled: true,\n autohide: true,\n },\n fontSize: 14,\n lineNumbersMinChars: 7,\n scrollBeyondLastLine: false,\n automaticLayout: true,\n wordBasedSuggestions: true,\n quickSuggestions: true,\n scrollbar: {\n verticalScrollbarSize: 8,\n horizontalScrollbarSize: 8,\n },\n scrollPredominantAxis: false,\n ...getMonacoOptions(),\n ...options,\n }}\n />\n </div>\n );\n}\n","export const DEFAULT_BABEL_URL =\n 'https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.22.20/babel.min.js';\n\nexport const DEFAULT_MONACO_URL =\n 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.43.0/min/vs';\n","import type { Node } from '@babel/types';\nimport React, { Component, HTMLAttributes } from 'react';\nimport {\n createGetImport,\n createObjectPattern,\n createVariableDeclaration,\n} from './ast';\nimport { getBabel } from './babel';\n\ninterface RunnerProps extends HTMLAttributes<HTMLDivElement> {\n code: string;\n language: string;\n getImport: (name: string, getDefault?: boolean) => void;\n}\n\ninterface RunnerState {\n error?: Error;\n comp: any;\n}\n\nconst DEBOUNCE_TIME = 800;\n\nclass Runner extends Component<RunnerProps, RunnerState> {\n static getDerivedStateFromError(error: Error) {\n return {\n error,\n comp: null,\n };\n }\n\n timer: any;\n\n constructor(props: RunnerProps) {\n super(props);\n\n this.state = {\n error: undefined,\n comp: null,\n };\n\n this.doCompile = this.doCompile.bind(this);\n this.waitCompile = this.waitCompile.bind(this);\n }\n\n waitCompile(targetCode: string) {\n if (this.timer) {\n clearTimeout(this.timer);\n }\n this.timer = setTimeout(() => {\n this.timer = null;\n this.doCompile(targetCode);\n }, DEBOUNCE_TIME);\n }\n\n async doCompile(targetCode: string) {\n const { language, getImport } = this.props;\n const babel = await getBabel();\n try {\n const presets = [\n [babel.availablePresets.react],\n [babel.availablePresets.env, { modules: 'commonjs' }],\n ];\n if (language === 'tsx' || language === 'ts') {\n presets.unshift([\n babel.availablePresets.typescript,\n {\n allExtensions: true,\n isTSX: language === 'tsx',\n },\n ]);\n }\n const result = babel.transform(targetCode, {\n sourceType: 'module',\n sourceMaps: 'inline',\n presets,\n plugins: [\n {\n pre() {\n this.hasReactImported = false;\n },\n visitor: {\n ImportDeclaration(path) {\n const pkg = path.node.source.value;\n const code: Node[] = [];\n const specifiers: (string | [string, string])[] = [];\n for (const specifier of path.node.specifiers) {\n if (specifier.local.name === 'React') {\n this.hasReactImported = true;\n }\n // import X from 'xxx'\n if (specifier.type === 'ImportDefaultSpecifier') {\n // const ${specifier.local.name} = __get_import()\n code.push(\n createVariableDeclaration(\n specifier.local.name,\n createGetImport(pkg, true),\n ),\n );\n }\n // import * as X from 'xxx'\n if (specifier.type === 'ImportNamespaceSpecifier') {\n // const ${specifier.local.name} = __get_import()\n code.push(\n createVariableDeclaration(\n specifier.local.name,\n createGetImport(pkg),\n ),\n );\n }\n // import { a, b, c } from 'xxx'\n if (specifier.type === 'ImportSpecifier') {\n if (\n 'name' in specifier.imported &&\n specifier.imported.name !== specifier.local.name\n ) {\n // const {${specifier.imported.name}: ${specifier.local.name}} = __get_import()\n specifiers.push([\n specifier.imported.name,\n specifier.local.name,\n ]);\n } else {\n // const {${specifier.local.name}} = __get_import()\n specifiers.push(specifier.local.name);\n }\n }\n }\n if (specifiers.length > 0) {\n code.push(\n createVariableDeclaration(\n createObjectPattern(specifiers),\n createGetImport(pkg),\n ),\n );\n }\n path.replaceWithMultiple(code);\n },\n },\n post(file) {\n // Auto import React\n if (!this.hasReactImported) {\n file.ast.program.body.unshift(\n createVariableDeclaration(\n 'React',\n createGetImport('react', true),\n ),\n );\n }\n },\n },\n ],\n });\n\n // Code has been updated\n if (targetCode !== this.props.code || !result || !result.code) {\n return;\n }\n\n const runExports: any = {};\n // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func\n const func = new Function('__get_import', 'exports', result.code);\n func(getImport, runExports);\n\n if (runExports.default) {\n this.setState({\n error: undefined,\n comp: React.createElement(runExports.default),\n });\n return;\n }\n\n this.setState({\n error: new Error('No default export'),\n });\n } catch (e) {\n // Code has been updated\n if (targetCode !== this.props.code) {\n return;\n }\n console.error(e);\n this.setState({\n error: e as Error,\n });\n }\n }\n\n componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {\n console.error(error);\n console.error(errorInfo);\n }\n\n componentDidMount() {\n this.doCompile(this.props.code);\n }\n\n componentDidUpdate(prevProps: RunnerProps) {\n if (prevProps.code !== this.props.code) {\n this.waitCompile(this.props.code);\n }\n }\n\n render() {\n const { className = '', code, language, getImport, ...rest } = this.props;\n const { error, comp } = this.state;\n\n return (\n <div className={`rspress-playground-runner ${className}`} {...rest}>\n {comp}\n {error && (\n <pre className=\"rspress-playground-error\">{error.message}</pre>\n )}\n </div>\n );\n }\n}\n\nexport { Runner };\n","import type {\n CallExpression,\n Expression,\n Identifier,\n ObjectPattern,\n ObjectProperty,\n VariableDeclaration,\n} from '@babel/types';\n\nexport function createVariableDeclaration(\n id: string | ObjectPattern,\n init: Expression,\n): VariableDeclaration {\n return {\n type: 'VariableDeclaration',\n declarations: [\n {\n type: 'VariableDeclarator',\n id:\n typeof id === 'string'\n ? {\n type: 'Identifier',\n name: id,\n }\n : id,\n init,\n },\n ],\n kind: 'const',\n };\n}\n\nfunction createIdentifier(name: string): Identifier {\n return {\n type: 'Identifier',\n name,\n };\n}\n\nfunction createObjectProperty(key: string, value: string): ObjectProperty {\n return {\n type: 'ObjectProperty',\n key: createIdentifier(key),\n computed: false,\n shorthand: key === value,\n value: createIdentifier(value),\n };\n}\n\nexport function createObjectPattern(\n names: (string | [string, string])[],\n): ObjectPattern {\n return {\n type: 'ObjectPattern',\n properties: names.map(name =>\n Array.isArray(name)\n ? createObjectProperty(name[0], name[1])\n : createObjectProperty(name, name),\n ),\n };\n}\n\nexport function createGetImport(\n name: string,\n getDefault?: boolean,\n): CallExpression {\n return {\n type: 'CallExpression',\n callee: {\n type: 'Identifier',\n name: '__get_import',\n },\n arguments: [\n {\n type: 'StringLiteral',\n value: name,\n },\n {\n type: 'BooleanLiteral',\n value: Boolean(getDefault),\n },\n ],\n };\n}\n","import type babel from '@babel/standalone';\n\ntype Babel = typeof babel;\n\ndeclare global {\n interface Window {\n Babel: Babel;\n }\n}\n\nfunction getBabel(): Babel | Promise<Babel> {\n if (window.Babel) {\n return window.Babel;\n }\n const el = document.getElementById('rspress-playground-babel');\n if (!el) {\n throw new Error('Babel not found');\n }\n return new Promise(resolve => {\n el.addEventListener('load', () => {\n resolve(window.Babel);\n });\n });\n}\n\nexport { getBabel };\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rspress/plugin-playground",
|
|
3
|
-
"version": "1.11.
|
|
3
|
+
"version": "1.11.2",
|
|
4
4
|
"description": "A plugin for rspress to preview the code block in markdown/mdx file.",
|
|
5
5
|
"bugs": "https://github.com/web-infra-dev/rspress/issues",
|
|
6
6
|
"repository": {
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
"@oxidation-compiler/napi": "^0.1.0",
|
|
38
38
|
"remark-gfm": "3.0.1",
|
|
39
39
|
"rspack-plugin-virtual-module": "0.1.12",
|
|
40
|
-
"@rspress/shared": "1.11.
|
|
40
|
+
"@rspress/shared": "1.11.2"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
43
|
"@babel/types": "^7.22.17",
|