@rspress/plugin-playground 1.0.0-beta.5 → 1.0.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/README.md +4 -0
- package/dist/cli/cjs/index.js +7 -0
- package/dist/cli/cjs/index.js.map +1 -1
- package/dist/cli/esm/index.js +144 -145
- package/dist/cli/esm/index.js.map +1 -1
- package/dist/web/cjs/index.js +7 -0
- package/dist/web/cjs/index.js.map +1 -1
- package/dist/web/esm/index.js +55 -62
- package/dist/web/esm/index.js.map +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"mappings":";;;;;;;;;;;AA0MA,SAASA,WAAWC,OAAK;AAEvB,QAAMC,SAAS;AACf,MAAIC,QAAQ;AAEZ,SAAO,EAAEA,QAAQF,MAAMG,QAAQ;AAC7BF,WAAOC,SAASE,QAAQJ,MAAME,MAAM;EACtC;AAEA,SAAOG,YAAYC;AAOnB,WAASA,OAAOC,YAAU;AACxB,QAAIL,SAAQ;AAEZ,WAAO,EAAEA,SAAQD,OAAOE,QAAQ;AAC9B,UAAIF,OAAOC,QAAOM,KAAK,MAAI,GAAKD;AAAa,eAAO;IACtD;AAEA,WAAO;EACT;AACF;AAQA,SAASE,aAAaC,OAAK;AACzB,SAAOL,YAAYM;AAMnB,WAASA,IAAIC,MAAI;AAEf,QAAIC;AAEJ,SAAKA,OAAOH,OAAO;AAEjB,UAAIE,KAAKC,SAASH,MAAMG;AAAM,eAAO;IACvC;AAEA,WAAO;EACT;AACF;AAQA,SAASC,YAAYJ,OAAK;AACxB,SAAOL,YAAYU;AAKnB,WAASA,KAAKH,MAAI;AAChB,WAAOA,QAAQA,KAAKG,SAASL;EAC/B;AACF;AAQA,SAASL,YAAYK,OAAK;AACxB,SAAOM;AAQP,WAASA,UAAUJ,SAASL,YAAU;AACpC,WAAOU,QACLL,QACE,OAAOA,SAAS,YAChB,UAAUA;IAEVK,QAAQP,MAAMF,KAAK,MAA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;WACR+F,WAAW9D,IACZ,CAACR,GAAGnF,UAAU,iBAAiBA,eAAeuI,QAAQpD,MAAM;QAE9D;WACGsE,WAAW9D,IAAI,CAACR,GAAGnF,UAAU,gBAAgBmF,SAASnF,SAAS;QAClE;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACAoD,KAAK;AAIP0E,8BAAwB6B,YAAY,+BAA+BjG;IACrE;IACAkG,eAAe;MACbpF,QAAQ;QACNqF,QAAQ;UACNC,0BAA0B7F,KAAK8F,UAAUpC;UACzCqC,8BAA8B/F,KAAK8F,UAAUnC;UAC7CqC,+BAA+BhG,KAAK8F,UAAUlC;QAChD;MACF;MACAqC,MAAM;QACJC,MAAMpC,SAASpC,IAAIyE,UAAQ;UACzBC,KAAK;UACLC,MAAM;UACN7E,OAAO;YACL8E,KAAK;YACLC,MAAMJ;YACNK,IAAI;UACN;QACF;MACF;MACAC,OAAO;;;QAGLC,QAAQ;UACNC,SAAS;YAAC9C;;QACZ;MACF;IACF;IACA+C,UAAU;MACR3B,eAAe;QACb;UAACrD;UAAc;YAAEC;YAAcC;YAAkBC;UAAe;;;MAElE8E,kBAAkB;QAChBrD,SACIA,SACAtE,MAAKC,KAAKE,YAAY,qBAAqB;;IAEnD;IACAyH,cAAc5H,MAAKC,KAAKE,YAAY,iBAAiB;EACvD;AACF;","names":["anyFactory","tests","checks","index","length","convert","castFactory","any","parameters","call","propsFactory","check","all","node","key","typeFactory","type","assertion","Boolean","ok","test","undefined","Array","isArray","Error","color","d","toResult","value","CONTINUE","EXIT","SKIP","visitParents","tree","visitor","reverse","is","step","factory","parents","name","tagName","Object","defineProperty","visit","result","subresult","offset","grandparents","children","concat","overload","parent","indexOf","path","join","RspackVirtualModulePlugin","staticPath","__dirname","oxc","parseImports","code","sourceExt","parsed","parseSync","sourceType","sourceFilename","ast","JSON","parse","program","body","forEach","statement","push","source","getNodeAttribute","attrName","attributes","find","attr","getNodeMeta","metaName","meta","split","item","x","startsWith","substring","fs","createPlaygroundNode","currentNode","attrs","assign","map","it","remarkPlugin","getRouteMeta","defaultDirection","editorPosition","routeMeta","vfile","route","absolutePath","history","src","demoPath","dirname","existsSync","direction","readFileSync","encoding","language","substr","lastIndexOf","lang","isPure","DEFAULT_BABEL_URL","DEFAULT_MONACO_URL","normalizeUrl","u","replace","pluginPlayground","options","render","include","babelUrl","monacoLoader","monacoOptions","playgroundVirtualModule","preloads","monacoPrefix","paths","vs","routeGenerated","routes","default","files","imports","Promise","filepath","_index","isMdxFile","createProcessor","remarkGFM","processor","format","extname","slice","remarkPlugins","readFile","thisImports","includes","e","console","error","importKeys","keys","writeModule","builderConfig","define","__PLAYGROUND_BABEL_URL__","stringify","__PLAYGROUND_MONACO_LOADER__","__PLAYGROUND_MONACO_OPTIONS__","html","tags","url","tag","head","rel","href","as","tools","rspack","plugins","markdown","globalComponents","globalStyles"],"sources":["../../../../../node_modules/.pnpm/unist-util-is@5.2.1/node_modules/unist-util-is/lib/home/runner/work/rspress/rspress/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/home/runner/work/rspress/rspress/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/home/runner/work/rspress/rspress/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/home/runner/work/rspress/rspress/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/home/runner/work/rspress/rspress/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/home/runner/work/rspress/rspress/node_modules/.pnpm/unist-util-visit@4.1.1/node_modules/unist-util-visit/index.js","../../../src/cli/home/runner/work/rspress/rspress/packages/plugin-playground/src/cli/index.ts","../../../src/cli/home/runner/work/rspress/rspress/packages/plugin-playground/src/cli/constant.ts","../../../src/cli/home/runner/work/rspress/rspress/packages/plugin-playground/src/cli/utils.ts","../../../src/cli/home/runner/work/rspress/rspress/packages/plugin-playground/src/cli/remarkPlugin.ts","../../../src/web/home/runner/work/rspress/rspress/packages/plugin-playground/src/web/constant.ts","../../../src/web/home/runner/work/rspress/rspress/packages/plugin-playground/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 { 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\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 } = 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 preloads.push(babelUrl || DEFAULT_BABEL_URL);\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 async routeGenerated(routes: RouteMeta[]) {\n const { default: fs } = await import('@modern-js/utils/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: any) => {\n if (node.lang === 'jsx' || node.lang === 'tsx') {\n const { value } = node;\n const isPure = node?.meta?.includes('pure');\n\n // do not anything for pure mode\n if (isPure) {\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 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_BABEL_URL__: JSON.stringify(babelUrl),\n __PLAYGROUND_MONACO_LOADER__: JSON.stringify(monacoLoader),\n __PLAYGROUND_MONACO_OPTIONS__: JSON.stringify(monacoOptions),\n },\n },\n html: {\n tags: preloads.map(url => ({\n tag: 'link',\n head: true,\n attrs: {\n rel: 'preload',\n href: url,\n as: 'script',\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, defaultDirection, editorPosition }],\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 path, { join } from 'path';\nimport { visit } from 'unist-util-visit';\nimport fs from '@modern-js/utils/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 defaultDirection: 'horizontal' | 'vertical';\n editorPosition: 'left' | 'right';\n}\n\n/**\n * remark plugin to transform code to demo\n */\nexport const remarkPlugin: Plugin<[RemarkPluginProps], Root> = ({\n getRouteMeta,\n defaultDirection,\n editorPosition,\n}) => {\n const routeMeta = getRouteMeta();\n\n return (tree, vfile) => {\n const route = routeMeta.find(\n meta => meta.absolutePath === (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 tree.children.forEach((node: any) => {\n if (node.type === 'mdxJsxFlowElement' && node.name === 'code') {\n const src = getNodeAttribute(node, 'src');\n if (!src) {\n return;\n }\n const demoPath = join(path.dirname(route.absolutePath), src);\n if (!fs.existsSync(demoPath)) {\n return;\n }\n const direction =\n getNodeAttribute(node, 'direction') || defaultDirection;\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 isPure = getNodeMeta(node, 'pure') === 'pure';\n\n // do nothing for pure mode\n if (isPure) {\n return;\n }\n\n const direction = getNodeMeta(node, 'direction') || defaultDirection;\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","const loadingMap = new Map<string, Promise<void>>();\n\nexport function loadScript(url: string): Promise<void> {\n const exists = loadingMap.get(url);\n if (exists) {\n return exists;\n }\n const n: Promise<void> = new Promise(resolve => {\n const e = document.createElement('script');\n e.src = url;\n e.onload = () => resolve();\n document.body.appendChild(e);\n });\n loadingMap.set(url, n);\n return n;\n}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QACN,QAAQ;AAAA,UACN,0BAA0B,KAAK,UAAU,QAAQ;AAAA,UACjD,8BAA8B,KAAK,UAAU,YAAY;AAAA,UACzD,+BAA+B,KAAK,UAAU,aAAa;AAAA,QAC7D;AAAA,MACF;AAAA,MACA,MAAM;AAAA,QACJ,MAAM,SAAS,IAAI,UAAQ;AAAA,UACzB,KAAK;AAAA,UACL,MAAM;AAAA,UACN,OAAO;AAAA,YACL,KAAK;AAAA,YACL,MAAM;AAAA,YACN,IAAI;AAAA,UACN;AAAA,QACF,EAAE;AAAA,MACJ;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,kBAAkB,eAAe,CAAC;AAAA,MACnE;AAAA,MACA,kBAAkB;AAAA,QAChB,SACI,SACAA,MAAK,KAAK,YAAY,qBAAqB,gBAAgB;AAAA,MACjE;AAAA,IACF;AAAA,IACA,cAAcA,MAAK,KAAK,YAAY,iBAAiB,SAAS;AAAA,EAChE;AACF;","names":["index","is","visit","path","routeMeta","fs","join","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 { 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\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 } = 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 preloads.push(babelUrl || DEFAULT_BABEL_URL);\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 async routeGenerated(routes: RouteMeta[]) {\n const { default: fs } = await import('@modern-js/utils/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: any) => {\n if (node.lang === 'jsx' || node.lang === 'tsx') {\n const { value } = node;\n const isPure = node?.meta?.includes('pure');\n\n // do not anything for pure mode\n if (isPure) {\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 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_BABEL_URL__: JSON.stringify(babelUrl),\n __PLAYGROUND_MONACO_LOADER__: JSON.stringify(monacoLoader),\n __PLAYGROUND_MONACO_OPTIONS__: JSON.stringify(monacoOptions),\n },\n },\n html: {\n tags: preloads.map(url => ({\n tag: 'link',\n head: true,\n attrs: {\n rel: 'preload',\n href: url,\n as: 'script',\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, defaultDirection, editorPosition }],\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 path, { join } from 'path';\nimport { visit } from 'unist-util-visit';\nimport fs from '@modern-js/utils/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 defaultDirection: 'horizontal' | 'vertical';\n editorPosition: 'left' | 'right';\n}\n\n/**\n * remark plugin to transform code to demo\n */\nexport const remarkPlugin: Plugin<[RemarkPluginProps], Root> = ({\n getRouteMeta,\n defaultDirection,\n editorPosition,\n}) => {\n const routeMeta = getRouteMeta();\n\n return (tree, vfile) => {\n const route = routeMeta.find(\n meta => meta.absolutePath === (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 tree.children.forEach((node: any) => {\n if (node.type === 'mdxJsxFlowElement' && node.name === 'code') {\n const src = getNodeAttribute(node, 'src');\n if (!src) {\n return;\n }\n const demoPath = join(path.dirname(route.absolutePath), src);\n if (!fs.existsSync(demoPath)) {\n return;\n }\n const direction =\n getNodeAttribute(node, 'direction') || defaultDirection;\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 isPure = getNodeMeta(node, 'pure') === 'pure';\n\n // do nothing for pure mode\n if (isPure) {\n return;\n }\n\n const direction = getNodeMeta(node, 'direction') || defaultDirection;\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","const loadingMap = new Map<string, Promise<void>>();\n\nexport function loadScript(url: string): Promise<void> {\n const exists = loadingMap.get(url);\n if (exists) {\n return exists;\n }\n const n: Promise<void> = new Promise(resolve => {\n const e = document.createElement('script');\n e.src = url;\n e.onload = () => resolve();\n document.body.appendChild(e);\n });\n loadingMap.set(url, n);\n return n;\n}\n\nexport function normalizeUrl(u: string) {\n return u.replace(/\\/\\//g, '/');\n}\n"]}
|
package/dist/web/cjs/index.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
|
+
"use strict";
|
|
1
2
|
var __create = Object.create;
|
|
2
3
|
var __defProp = Object.defineProperty;
|
|
3
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
5
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
6
|
var __getProtoOf = Object.getPrototypeOf;
|
|
6
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
7
9
|
var __export = (target, all) => {
|
|
8
10
|
for (var name in all)
|
|
9
11
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
@@ -25,6 +27,10 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
25
27
|
mod
|
|
26
28
|
));
|
|
27
29
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
30
|
+
var __publicField = (obj, key, value) => {
|
|
31
|
+
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
32
|
+
return value;
|
|
33
|
+
};
|
|
28
34
|
|
|
29
35
|
// src/web/index.ts
|
|
30
36
|
var web_exports = {};
|
|
@@ -197,6 +203,7 @@ var import_jsx_runtime2 = require("react/jsx-runtime");
|
|
|
197
203
|
var Runner = class extends import_react2.Component {
|
|
198
204
|
constructor(props) {
|
|
199
205
|
super(props);
|
|
206
|
+
__publicField(this, "timer");
|
|
200
207
|
this.state = {
|
|
201
208
|
error: void 0,
|
|
202
209
|
comp: null
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAIO;;;ACHP,mBAGO;;;ACJA,IAAM,oBACX;AAEK,IAAM,qBACX;;;AD+CI;AArCN,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,GAAP;AAAA,EAEF;AAEA,sBAAO,OAAO,YAAY;AAC5B;AACA,WAAW;AAEX,SAAS,mBAAmB;AAC1B,MAAI;AACF,WAAO;AAAA,EACT,SAAS,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WAAW,6BAA6B,aAAc,GAAG,MAC5D,uDAAC,UAAK,OAAO,EAAE,OAAO,MAAM,GAAI,gBAAM,SAAQ,GAChD;AAAA,IAEJ;AAEA,WACE,6CAAC,SAAI,WAAW,6BAA6B,aAAc,GAAG,MAC3D,gBACH;AAAA,EAEJ;AACF;","names":[],"sources":["../../../src/web/index.ts","../../../src/web/editor.tsx","../../../src/web/constant.ts","../../../src/web/runner.tsx","../../../src/web/ast.ts","../../../src/web/utils.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 from 'react';\nimport MonacoEditor, {\n loader,\n EditorProps as MonacoEditorProps,\n} from '@monaco-editor/react';\nimport { DEFAULT_MONACO_URL } from './constant';\n\n// inject by builder in cli/index.ts\n// see: https://modernjs.dev/builder/api/config-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 = '', ...rest } = props || {};\n\n return (\n <div className={`rspress-playground-editor ${className}`}>\n <MonacoEditor\n {...rest}\n theme=\"light\"\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\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 }, 600);\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 presets,\n plugins: [\n {\n visitor: {\n ImportDeclaration(path) {\n const pkg = path.node.source.value;\n const code: Node[] = [];\n for (const specifier of path.node.specifiers) {\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 code.push(\n createVariableDeclaration(\n createObjectPattern([specifier.local.name]),\n createGetImport(pkg),\n ),\n );\n }\n }\n path.replaceWithMultiple(code);\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 comp: null,\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 comp: null,\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 if (error) {\n return (\n <div className={`rspress-playground-runner ${className}`} {...rest}>\n <span style={{ color: 'red' }}>{error.message}</span>\n </div>\n );\n }\n\n return (\n <div className={`rspress-playground-runner ${className}`} {...rest}>\n {comp}\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","const loadingMap = new Map<string, Promise<void>>();\n\nexport function loadScript(url: string): Promise<void> {\n const exists = loadingMap.get(url);\n if (exists) {\n return exists;\n }\n const n: Promise<void> = new Promise(resolve => {\n const e = document.createElement('script');\n e.src = url;\n e.onload = () => resolve();\n document.body.appendChild(e);\n });\n loadingMap.set(url, n);\n return n;\n}\n\nexport function normalizeUrl(u: string) {\n return u.replace(/\\/\\//g, '/');\n}\n","import type babel from '@babel/standalone';\nimport { DEFAULT_BABEL_URL } from './constant';\nimport { loadScript } from './utils';\n\ndeclare global {\n // inject by builder in cli/index.ts\n // see: https://modernjs.dev/builder/api/config-source.html#sourcedefine\n const __PLAYGROUND_BABEL_URL__: any;\n interface Window {\n Babel: typeof babel;\n }\n}\n\nasync function getBabel() {\n if (!window.Babel) {\n let babelUrl = DEFAULT_BABEL_URL;\n try {\n const u = __PLAYGROUND_BABEL_URL__;\n if (u) {\n babelUrl = u;\n }\n } catch (e) {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KAAK,MAAM,MAAM;AAClC;AAAA,MACF;AACA,cAAQ,MAAM,CAAC;AACf,WAAK,SAAS;AAAA,QACZ,OAAO;AAAA,QACP,MAAM;AAAA,MACR,CAAC;AAAA,IACH;AAAA,EACF;AAAA,EAEA,kBAAkB,OAAc,WAA4B;AAC1D,YAAQ,MAAM,KAAK;AACnB,YAAQ,MAAM,SAAS;AAAA,EACzB;AAAA,EAEA,oBAAoB;AAClB,SAAK,UAAU,KAAK,MAAM,IAAI;AAAA,EAChC;AAAA,EAEA,mBAAmB,WAAwB;AACzC,QAAI,UAAU,SAAS,KAAK,MAAM,MAAM;AACtC,WAAK,YAAY,KAAK,MAAM,IAAI;AAAA,IAClC;AAAA,EACF;AAAA,EAEA,SAAS;AACP,UAAM,EAAE,YAAY,IAAI,MAAM,UAAU,WAAW,GAAG,KAAK,IAAI,KAAK;AACpE,UAAM,EAAE,OAAO,KAAK,IAAI,KAAK;AAE7B,QAAI,OAAO;AACT,aACE,6CAAC,SAAI,WAAW,6BAA6B,SAAS,IAAK,GAAG,MAC5D,uDAAC,UAAK,OAAO,EAAE,OAAO,MAAM,GAAI,gBAAM,SAAQ,GAChD;AAAA,IAEJ;AAEA,WACE,6CAAC,SAAI,WAAW,6BAA6B,SAAS,IAAK,GAAG,MAC3D,gBACH;AAAA,EAEJ;AACF;","names":[],"sources":["../../../src/web/index.ts","../../../src/web/editor.tsx","../../../src/web/constant.ts","../../../src/web/runner.tsx","../../../src/web/ast.ts","../../../src/web/utils.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 from 'react';\nimport MonacoEditor, {\n loader,\n EditorProps as MonacoEditorProps,\n} from '@monaco-editor/react';\nimport { DEFAULT_MONACO_URL } from './constant';\n\n// inject by builder in cli/index.ts\n// see: https://modernjs.dev/builder/api/config-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 = '', ...rest } = props || {};\n\n return (\n <div className={`rspress-playground-editor ${className}`}>\n <MonacoEditor\n {...rest}\n theme=\"light\"\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\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 }, 600);\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 presets,\n plugins: [\n {\n visitor: {\n ImportDeclaration(path) {\n const pkg = path.node.source.value;\n const code: Node[] = [];\n for (const specifier of path.node.specifiers) {\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 code.push(\n createVariableDeclaration(\n createObjectPattern([specifier.local.name]),\n createGetImport(pkg),\n ),\n );\n }\n }\n path.replaceWithMultiple(code);\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 comp: null,\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 comp: null,\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 if (error) {\n return (\n <div className={`rspress-playground-runner ${className}`} {...rest}>\n <span style={{ color: 'red' }}>{error.message}</span>\n </div>\n );\n }\n\n return (\n <div className={`rspress-playground-runner ${className}`} {...rest}>\n {comp}\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","const loadingMap = new Map<string, Promise<void>>();\n\nexport function loadScript(url: string): Promise<void> {\n const exists = loadingMap.get(url);\n if (exists) {\n return exists;\n }\n const n: Promise<void> = new Promise(resolve => {\n const e = document.createElement('script');\n e.src = url;\n e.onload = () => resolve();\n document.body.appendChild(e);\n });\n loadingMap.set(url, n);\n return n;\n}\n\nexport function normalizeUrl(u: string) {\n return u.replace(/\\/\\//g, '/');\n}\n","import type babel from '@babel/standalone';\nimport { DEFAULT_BABEL_URL } from './constant';\nimport { loadScript } from './utils';\n\ndeclare global {\n // inject by builder in cli/index.ts\n // see: https://modernjs.dev/builder/api/config-source.html#sourcedefine\n const __PLAYGROUND_BABEL_URL__: any;\n interface Window {\n Babel: typeof babel;\n }\n}\n\nasync function getBabel() {\n if (!window.Babel) {\n let babelUrl = DEFAULT_BABEL_URL;\n try {\n const u = __PLAYGROUND_BABEL_URL__;\n if (u) {\n babelUrl = u;\n }\n } catch (e) {\n // ignore\n }\n await loadScript(babelUrl);\n }\n return window.Babel;\n}\n\nexport { getBabel };\n"]}
|
package/dist/web/esm/index.js
CHANGED
|
@@ -1,15 +1,28 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
3
|
+
var __publicField = (obj, key, value) => {
|
|
4
|
+
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
5
|
+
return value;
|
|
6
|
+
};
|
|
7
|
+
|
|
1
8
|
// src/web/index.ts
|
|
2
|
-
import {
|
|
9
|
+
import {
|
|
10
|
+
default as default2,
|
|
11
|
+
loader as loader2,
|
|
12
|
+
EditorProps
|
|
13
|
+
} from "@monaco-editor/react";
|
|
3
14
|
|
|
4
15
|
// src/web/editor.tsx
|
|
5
|
-
import {
|
|
6
|
-
|
|
16
|
+
import MonacoEditor, {
|
|
17
|
+
loader
|
|
18
|
+
} from "@monaco-editor/react";
|
|
7
19
|
|
|
8
20
|
// src/web/constant.ts
|
|
9
21
|
var DEFAULT_BABEL_URL = "https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.22.20/babel.min.js";
|
|
10
22
|
var DEFAULT_MONACO_URL = "https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.43.0/min/vs";
|
|
11
23
|
|
|
12
24
|
// src/web/editor.tsx
|
|
25
|
+
import { jsx } from "react/jsx-runtime";
|
|
13
26
|
function initLoader() {
|
|
14
27
|
let loaderConfig = {
|
|
15
28
|
paths: {
|
|
@@ -35,9 +48,9 @@ function getMonacoOptions() {
|
|
|
35
48
|
}
|
|
36
49
|
function Editor(props) {
|
|
37
50
|
const { options, className = "", ...rest } = props || {};
|
|
38
|
-
return /* @__PURE__ */
|
|
39
|
-
|
|
40
|
-
|
|
51
|
+
return /* @__PURE__ */ jsx("div", { className: `rspress-playground-editor ${className}`, children: /* @__PURE__ */ jsx(
|
|
52
|
+
MonacoEditor,
|
|
53
|
+
{
|
|
41
54
|
...rest,
|
|
42
55
|
theme: "light",
|
|
43
56
|
options: {
|
|
@@ -59,12 +72,11 @@ function Editor(props) {
|
|
|
59
72
|
...getMonacoOptions(),
|
|
60
73
|
...options
|
|
61
74
|
}
|
|
62
|
-
}
|
|
63
|
-
});
|
|
75
|
+
}
|
|
76
|
+
) });
|
|
64
77
|
}
|
|
65
78
|
|
|
66
79
|
// src/web/runner.tsx
|
|
67
|
-
import { jsx as _jsx2 } from "react/jsx-runtime";
|
|
68
80
|
import React, { Component } from "react";
|
|
69
81
|
|
|
70
82
|
// src/web/ast.ts
|
|
@@ -157,20 +169,18 @@ async function getBabel() {
|
|
|
157
169
|
}
|
|
158
170
|
|
|
159
171
|
// src/web/runner.tsx
|
|
160
|
-
|
|
161
|
-
if (key in obj) {
|
|
162
|
-
Object.defineProperty(obj, key, {
|
|
163
|
-
value,
|
|
164
|
-
enumerable: true,
|
|
165
|
-
configurable: true,
|
|
166
|
-
writable: true
|
|
167
|
-
});
|
|
168
|
-
} else {
|
|
169
|
-
obj[key] = value;
|
|
170
|
-
}
|
|
171
|
-
return obj;
|
|
172
|
-
}
|
|
172
|
+
import { jsx as jsx2 } from "react/jsx-runtime";
|
|
173
173
|
var Runner = class extends Component {
|
|
174
|
+
constructor(props) {
|
|
175
|
+
super(props);
|
|
176
|
+
__publicField(this, "timer");
|
|
177
|
+
this.state = {
|
|
178
|
+
error: void 0,
|
|
179
|
+
comp: null
|
|
180
|
+
};
|
|
181
|
+
this.doCompile = this.doCompile.bind(this);
|
|
182
|
+
this.waitCompile = this.waitCompile.bind(this);
|
|
183
|
+
}
|
|
174
184
|
static getDerivedStateFromError(error) {
|
|
175
185
|
return {
|
|
176
186
|
error,
|
|
@@ -191,15 +201,8 @@ var Runner = class extends Component {
|
|
|
191
201
|
const babel = await getBabel();
|
|
192
202
|
try {
|
|
193
203
|
const presets = [
|
|
194
|
-
[
|
|
195
|
-
|
|
196
|
-
],
|
|
197
|
-
[
|
|
198
|
-
babel.availablePresets.env,
|
|
199
|
-
{
|
|
200
|
-
modules: "commonjs"
|
|
201
|
-
}
|
|
202
|
-
]
|
|
204
|
+
[babel.availablePresets.react],
|
|
205
|
+
[babel.availablePresets.env, { modules: "commonjs" }]
|
|
203
206
|
];
|
|
204
207
|
if (language === "tsx" || language === "ts") {
|
|
205
208
|
presets.unshift([
|
|
@@ -221,15 +224,28 @@ var Runner = class extends Component {
|
|
|
221
224
|
const code = [];
|
|
222
225
|
for (const specifier of path.node.specifiers) {
|
|
223
226
|
if (specifier.type === "ImportDefaultSpecifier") {
|
|
224
|
-
code.push(
|
|
227
|
+
code.push(
|
|
228
|
+
createVariableDeclaration(
|
|
229
|
+
specifier.local.name,
|
|
230
|
+
createGetImport(pkg, true)
|
|
231
|
+
)
|
|
232
|
+
);
|
|
225
233
|
}
|
|
226
234
|
if (specifier.type === "ImportNamespaceSpecifier") {
|
|
227
|
-
code.push(
|
|
235
|
+
code.push(
|
|
236
|
+
createVariableDeclaration(
|
|
237
|
+
specifier.local.name,
|
|
238
|
+
createGetImport(pkg)
|
|
239
|
+
)
|
|
240
|
+
);
|
|
228
241
|
}
|
|
229
242
|
if (specifier.type === "ImportSpecifier") {
|
|
230
|
-
code.push(
|
|
231
|
-
|
|
232
|
-
|
|
243
|
+
code.push(
|
|
244
|
+
createVariableDeclaration(
|
|
245
|
+
createObjectPattern([specifier.local.name]),
|
|
246
|
+
createGetImport(pkg)
|
|
247
|
+
)
|
|
248
|
+
);
|
|
233
249
|
}
|
|
234
250
|
}
|
|
235
251
|
path.replaceWithMultiple(code);
|
|
@@ -247,7 +263,7 @@ var Runner = class extends Component {
|
|
|
247
263
|
if (runExports.default) {
|
|
248
264
|
this.setState({
|
|
249
265
|
error: void 0,
|
|
250
|
-
comp:
|
|
266
|
+
comp: React.createElement(runExports.default)
|
|
251
267
|
});
|
|
252
268
|
return;
|
|
253
269
|
}
|
|
@@ -282,32 +298,9 @@ var Runner = class extends Component {
|
|
|
282
298
|
const { className = "", code, language, getImport, ...rest } = this.props;
|
|
283
299
|
const { error, comp } = this.state;
|
|
284
300
|
if (error) {
|
|
285
|
-
return /* @__PURE__ */
|
|
286
|
-
className: `rspress-playground-runner ${className}`,
|
|
287
|
-
...rest,
|
|
288
|
-
children: /* @__PURE__ */ _jsx2("span", {
|
|
289
|
-
style: {
|
|
290
|
-
color: "red"
|
|
291
|
-
},
|
|
292
|
-
children: error.message
|
|
293
|
-
})
|
|
294
|
-
});
|
|
301
|
+
return /* @__PURE__ */ jsx2("div", { className: `rspress-playground-runner ${className}`, ...rest, children: /* @__PURE__ */ jsx2("span", { style: { color: "red" }, children: error.message }) });
|
|
295
302
|
}
|
|
296
|
-
return /* @__PURE__ */
|
|
297
|
-
className: `rspress-playground-runner ${className}`,
|
|
298
|
-
...rest,
|
|
299
|
-
children: comp
|
|
300
|
-
});
|
|
301
|
-
}
|
|
302
|
-
constructor(props) {
|
|
303
|
-
super(props);
|
|
304
|
-
_define_property(this, "timer", void 0);
|
|
305
|
-
this.state = {
|
|
306
|
-
error: void 0,
|
|
307
|
-
comp: null
|
|
308
|
-
};
|
|
309
|
-
this.doCompile = this.doCompile.bind(this);
|
|
310
|
-
this.waitCompile = this.waitCompile.bind(this);
|
|
303
|
+
return /* @__PURE__ */ jsx2("div", { className: `rspress-playground-runner ${className}`, ...rest, children: comp });
|
|
311
304
|
}
|
|
312
305
|
};
|
|
313
306
|
export {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"mappings":";AAAA,SACaA,WAAXC,UACUC,UAAVC,SACeC,mBACV;;;;ACHP,OAAOJ,gBACLG,cAEK;;;ACJA,IAAME,oBACX;AAEK,IAAMC,qBACX;;;ADUF,SAASC;AACP,MAAIC,eAAe;IACjBC,OAAO;MACLC,IAAIJ;IACN;EACF;AAEA,MAAI;AACF,UAAMK,OAAOC,OAAOD,KAAKE;AAEzB,QAAIF,KAAKG,SAAS,GAAG;AACnBN,qBAAeK;IACjB;EACF,SAASE,GAAP;EAEF;AAEAZ,SAAOa,OAAOR;AAChB;AACAD;AAEA,SAASU;AACP,MAAI;AACF,WAAOC;EACT,SAASH,GAAP;EAEF;AACA,SAAO,CAAC;AACV;AAIO,SAASI,OAAOC,OAAkB;AACvC,QAAM,EAAEC,SAASC,YAAY,IAAI,GAAGC,SAASH,SAAS,CAAC;AAEvD,SACE,qBAACI;IAAIF,WAAW,6BAA6BA;cAC3C,qBAACtB;MACE,GAAGuB;MACJE,OAAM;MACNJ,SAAS;QACPK,SAAS;UACPC,SAAS;UACTC,UAAU;QACZ;QACAC,UAAU;QACVC,qBAAqB;QACrBC,sBAAsB;QACtBC,iBAAiB;QACjBC,sBAAsB;QACtBC,kBAAkB;QAClBC,WAAW;UACTC,uBAAuB;UACvBC,yBAAyB;QAC3B;QACAC,uBAAuB;QACvB,GAAGrB;QACH,GAAGI;MACL;;;AAIR;;;;AE3EA,OAAOkB,SAASC,iBAAiC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A;AAHRsE;AAKE,SAAK6C,QAAQ;MACXjD,OAAOwC;MACPvC,MAAM;IACR;AAEA,SAAKM,YAAY,KAAKA,UAAUgD,KAAK,IAAI;AACzC,SAAKrD,cAAc,KAAKA,YAAYqD,KAAK,IAAI;EAC/C;AAiJF;","names":["MonacoEditor","default","MonacoEditorLoader","loader","MonacoEditorProps","DEFAULT_BABEL_URL","DEFAULT_MONACO_URL","initLoader","loaderConfig","paths","vs","keys","Object","__PLAYGROUND_MONACO_LOADER__","length","e","config","getMonacoOptions","__PLAYGROUND_MONACO_OPTIONS__","Editor","props","options","className","rest","div","theme","minimap","enabled","autohide","fontSize","lineNumbersMinChars","scrollBeyondLastLine","automaticLayout","wordBasedSuggestions","quickSuggestions","scrollbar","verticalScrollbarSize","horizontalScrollbarSize","scrollPredominantAxis","React","Component","createVariableDeclaration","id","init","type","declarations","name","kind","createObjectPattern","names","properties","map","key","computed","method","shorthand","value","createGetImport","getDefault","callee","arguments","Boolean","loadingMap","Map","loadScript","url","exists","get","n","Promise","resolve","document","createElement","src","onload","body","appendChild","set","getBabel","window","Babel","babelUrl","u","__PLAYGROUND_BABEL_URL__","Runner","getDerivedStateFromError","error","comp","waitCompile","targetCode","timer","clearTimeout","setTimeout","doCompile","language","getImport","babel","presets","availablePresets","react","env","modules","unshift","typescript","allExtensions","isTSX","result","transform","sourceType","plugins","visitor","ImportDeclaration","path","pkg","node","source","code","specifier","specifiers","push","local","replaceWithMultiple","runExports","func","Function","setState","undefined","Error","console","componentDidCatch","errorInfo","componentDidMount","componentDidUpdate","prevProps","render","state","span","style","color","message","constructor","bind"],"sources":["../../../src/web/home/runner/work/rspress/rspress/packages/plugin-playground/src/web/index.ts","../../../src/web/home/runner/work/rspress/rspress/packages/plugin-playground/src/web/editor.tsx","../../../src/web/home/runner/work/rspress/rspress/packages/plugin-playground/src/web/constant.ts","../../../src/web/home/runner/work/rspress/rspress/packages/plugin-playground/src/web/runner.tsx","../../../src/web/home/runner/work/rspress/rspress/packages/plugin-playground/src/web/ast.ts","../../../src/web/home/runner/work/rspress/rspress/packages/plugin-playground/src/web/utils.ts","../../../src/web/home/runner/work/rspress/rspress/packages/plugin-playground/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 from 'react';\nimport MonacoEditor, {\n loader,\n EditorProps as MonacoEditorProps,\n} from '@monaco-editor/react';\nimport { DEFAULT_MONACO_URL } from './constant';\n\n// inject by builder in cli/index.ts\n// see: https://modernjs.dev/builder/api/config-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 = '', ...rest } = props || {};\n\n return (\n <div className={`rspress-playground-editor ${className}`}>\n <MonacoEditor\n {...rest}\n theme=\"light\"\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\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 }, 600);\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 presets,\n plugins: [\n {\n visitor: {\n ImportDeclaration(path) {\n const pkg = path.node.source.value;\n const code: Node[] = [];\n for (const specifier of path.node.specifiers) {\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 code.push(\n createVariableDeclaration(\n createObjectPattern([specifier.local.name]),\n createGetImport(pkg),\n ),\n );\n }\n }\n path.replaceWithMultiple(code);\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 comp: null,\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 comp: null,\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 if (error) {\n return (\n <div className={`rspress-playground-runner ${className}`} {...rest}>\n <span style={{ color: 'red' }}>{error.message}</span>\n </div>\n );\n }\n\n return (\n <div className={`rspress-playground-runner ${className}`} {...rest}>\n {comp}\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","const loadingMap = new Map<string, Promise<void>>();\n\nexport function loadScript(url: string): Promise<void> {\n const exists = loadingMap.get(url);\n if (exists) {\n return exists;\n }\n const n: Promise<void> = new Promise(resolve => {\n const e = document.createElement('script');\n e.src = url;\n e.onload = () => resolve();\n document.body.appendChild(e);\n });\n loadingMap.set(url, n);\n return n;\n}\n\nexport function normalizeUrl(u: string) {\n return u.replace(/\\/\\//g, '/');\n}\n","import type babel from '@babel/standalone';\nimport { DEFAULT_BABEL_URL } from './constant';\nimport { loadScript } from './utils';\n\ndeclare global {\n // inject by builder in cli/index.ts\n // see: https://modernjs.dev/builder/api/config-source.html#sourcedefine\n const __PLAYGROUND_BABEL_URL__: any;\n interface Window {\n Babel: typeof babel;\n }\n}\n\nasync function getBabel() {\n if (!window.Babel) {\n let babelUrl = DEFAULT_BABEL_URL;\n try {\n const u = __PLAYGROUND_BABEL_URL__;\n if (u) {\n babelUrl = u;\n }\n } catch (e) {\n // ignore\n }\n await loadScript(babelUrl);\n }\n return window.Babel;\n}\n\nexport { getBabel };\n"]}
|
|
1
|
+
{"version":3,"mappings":";;;;;;;;AAAA;AAAA,EACa,WAAXA;AAAA,EACU,UAAVC;AAAA,EACe;AAAA,OACV;;;ACHP,OAAO;AAAA,EACL;A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AAM,KAAK;AACnB,YAAQ,MAAM,SAAS;AAAA,EACzB;AAAA,EAEA,oBAAoB;AAClB,SAAK,UAAU,KAAK,MAAM,IAAI;AAAA,EAChC;AAAA,EAEA,mBAAmB,WAAwB;AACzC,QAAI,UAAU,SAAS,KAAK,MAAM,MAAM;AACtC,WAAK,YAAY,KAAK,MAAM,IAAI;AAAA,IAClC;AAAA,EACF;AAAA,EAEA,SAAS;AACP,UAAM,EAAE,YAAY,IAAI,MAAM,UAAU,WAAW,GAAG,KAAK,IAAI,KAAK;AACpE,UAAM,EAAE,OAAO,KAAK,IAAI,KAAK;AAE7B,QAAI,OAAO;AACT,aACE,qBAAC,SAAI,WAAW,6BAA6B,SAAS,IAAK,GAAG,MAC5D,+BAAC,UAAK,OAAO,EAAE,OAAO,MAAM,GAAI,gBAAM,SAAQ,GAChD;AAAA,IAEJ;AAEA,WACE,qBAAC,SAAI,WAAW,6BAA6B,SAAS,IAAK,GAAG,MAC3D,gBACH;AAAA,EAEJ;AACF;","names":["default","loader"],"sources":["../../../src/web/index.ts","../../../src/web/editor.tsx","../../../src/web/constant.ts","../../../src/web/runner.tsx","../../../src/web/ast.ts","../../../src/web/utils.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 from 'react';\nimport MonacoEditor, {\n loader,\n EditorProps as MonacoEditorProps,\n} from '@monaco-editor/react';\nimport { DEFAULT_MONACO_URL } from './constant';\n\n// inject by builder in cli/index.ts\n// see: https://modernjs.dev/builder/api/config-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 = '', ...rest } = props || {};\n\n return (\n <div className={`rspress-playground-editor ${className}`}>\n <MonacoEditor\n {...rest}\n theme=\"light\"\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\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 }, 600);\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 presets,\n plugins: [\n {\n visitor: {\n ImportDeclaration(path) {\n const pkg = path.node.source.value;\n const code: Node[] = [];\n for (const specifier of path.node.specifiers) {\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 code.push(\n createVariableDeclaration(\n createObjectPattern([specifier.local.name]),\n createGetImport(pkg),\n ),\n );\n }\n }\n path.replaceWithMultiple(code);\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 comp: null,\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 comp: null,\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 if (error) {\n return (\n <div className={`rspress-playground-runner ${className}`} {...rest}>\n <span style={{ color: 'red' }}>{error.message}</span>\n </div>\n );\n }\n\n return (\n <div className={`rspress-playground-runner ${className}`} {...rest}>\n {comp}\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","const loadingMap = new Map<string, Promise<void>>();\n\nexport function loadScript(url: string): Promise<void> {\n const exists = loadingMap.get(url);\n if (exists) {\n return exists;\n }\n const n: Promise<void> = new Promise(resolve => {\n const e = document.createElement('script');\n e.src = url;\n e.onload = () => resolve();\n document.body.appendChild(e);\n });\n loadingMap.set(url, n);\n return n;\n}\n\nexport function normalizeUrl(u: string) {\n return u.replace(/\\/\\//g, '/');\n}\n","import type babel from '@babel/standalone';\nimport { DEFAULT_BABEL_URL } from './constant';\nimport { loadScript } from './utils';\n\ndeclare global {\n // inject by builder in cli/index.ts\n // see: https://modernjs.dev/builder/api/config-source.html#sourcedefine\n const __PLAYGROUND_BABEL_URL__: any;\n interface Window {\n Babel: typeof babel;\n }\n}\n\nasync function getBabel() {\n if (!window.Babel) {\n let babelUrl = DEFAULT_BABEL_URL;\n try {\n const u = __PLAYGROUND_BABEL_URL__;\n if (u) {\n babelUrl = u;\n }\n } catch (e) {\n // ignore\n }\n await loadScript(babelUrl);\n }\n return window.Babel;\n}\n\nexport { getBabel };\n"]}
|