@rspress/plugin-playground 0.0.0-nightly-20230920160336 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/cjs/index.js +27 -0
- package/dist/cli/cjs/index.js.map +1 -1
- package/dist/cli/esm/index.d.ts +1 -0
- package/dist/cli/esm/index.js +27 -1
- package/dist/cli/esm/index.js.map +1 -1
- package/dist/web/cjs/index.js +44 -3
- package/dist/web/cjs/index.js.map +1 -1
- package/dist/web/esm/index.d.ts +1 -1
- package/dist/web/esm/index.js +42 -3
- package/dist/web/esm/index.js.map +1 -1
- package/package.json +4 -5
package/dist/web/cjs/index.js
CHANGED
|
@@ -40,10 +40,18 @@ var import_react3 = __toESM(require("@monaco-editor/react"));
|
|
|
40
40
|
|
|
41
41
|
// src/web/editor.tsx
|
|
42
42
|
var import_react = __toESM(require("@monaco-editor/react"));
|
|
43
|
+
|
|
44
|
+
// src/web/constant.ts
|
|
45
|
+
var DEFAULT_BABEL_URL = "https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.22.20/babel.min.js";
|
|
46
|
+
var DEFAULT_MONACO_URL = "https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.43.0/min/vs";
|
|
47
|
+
|
|
48
|
+
// src/web/editor.tsx
|
|
43
49
|
var import_jsx_runtime = require("react/jsx-runtime");
|
|
44
50
|
function initLoader() {
|
|
45
51
|
let loaderConfig = {
|
|
46
|
-
paths: {
|
|
52
|
+
paths: {
|
|
53
|
+
vs: DEFAULT_MONACO_URL
|
|
54
|
+
}
|
|
47
55
|
};
|
|
48
56
|
try {
|
|
49
57
|
const keys = Object.keys(__PLAYGROUND_MONACO_LOADER__);
|
|
@@ -93,7 +101,6 @@ function Editor(props) {
|
|
|
93
101
|
}
|
|
94
102
|
|
|
95
103
|
// src/web/runner.tsx
|
|
96
|
-
var babel = __toESM(require("@babel/standalone"));
|
|
97
104
|
var import_react2 = __toESM(require("react"));
|
|
98
105
|
|
|
99
106
|
// src/web/ast.ts
|
|
@@ -152,6 +159,39 @@ function createGetImport(name, getDefault) {
|
|
|
152
159
|
};
|
|
153
160
|
}
|
|
154
161
|
|
|
162
|
+
// src/web/utils.ts
|
|
163
|
+
var loadingMap = /* @__PURE__ */ new Map();
|
|
164
|
+
function loadScript(url) {
|
|
165
|
+
const exists = loadingMap.get(url);
|
|
166
|
+
if (exists) {
|
|
167
|
+
return exists;
|
|
168
|
+
}
|
|
169
|
+
const n = new Promise((resolve) => {
|
|
170
|
+
const e = document.createElement("script");
|
|
171
|
+
e.src = url;
|
|
172
|
+
e.onload = () => resolve();
|
|
173
|
+
document.body.appendChild(e);
|
|
174
|
+
});
|
|
175
|
+
loadingMap.set(url, n);
|
|
176
|
+
return n;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// src/web/babel.ts
|
|
180
|
+
async function getBabel() {
|
|
181
|
+
if (!window.Babel) {
|
|
182
|
+
let babelUrl = DEFAULT_BABEL_URL;
|
|
183
|
+
try {
|
|
184
|
+
const u = __PLAYGROUND_BABEL_URL__;
|
|
185
|
+
if (u) {
|
|
186
|
+
babelUrl = u;
|
|
187
|
+
}
|
|
188
|
+
} catch (e) {
|
|
189
|
+
}
|
|
190
|
+
await loadScript(babelUrl);
|
|
191
|
+
}
|
|
192
|
+
return window.Babel;
|
|
193
|
+
}
|
|
194
|
+
|
|
155
195
|
// src/web/runner.tsx
|
|
156
196
|
var import_jsx_runtime2 = require("react/jsx-runtime");
|
|
157
197
|
var Runner = class extends import_react2.Component {
|
|
@@ -179,8 +219,9 @@ var Runner = class extends import_react2.Component {
|
|
|
179
219
|
this.doCompile(targetCode);
|
|
180
220
|
}, 600);
|
|
181
221
|
}
|
|
182
|
-
doCompile(targetCode) {
|
|
222
|
+
async doCompile(targetCode) {
|
|
183
223
|
const { language, getImport } = this.props;
|
|
224
|
+
const babel = await getBabel();
|
|
184
225
|
try {
|
|
185
226
|
const presets = [
|
|
186
227
|
[babel.availablePres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AAC,SAAI,WAAW,6BAA6B,aAAc,GAAG,MAC3D,gBACH;AAAA,EAEJ;AACF;","names":[],"sources":["../../../src/web/index.ts","../../../src/web/editor.tsx","../../../src/web/runner.tsx","../../../src/web/ast.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';\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: { vs: 'https://unpkg.com/monaco-editor@0.43.0/min/vs' },\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","import * as babel from '@babel/standalone';\nimport type { Node } from '@babel/types';\nimport React, { Component, HTMLAttributes } from 'react';\nimport {\n createGetImport,\n createObjectPattern,\n createVariableDeclaration,\n} from './ast';\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 doCompile(targetCode: string) {\n const { language, getImport } = this.props;\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"]}
|
|
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,GAAP;AAAA,EAEF;AACA,SAAO,CAAC;AACV;AAIO,SAAS,OAAO,OAAoB;AACzC,QAAM,EAAE,SAAS,YAAY,IAAI,GAAG,KAAK,IAAI,SAAS,CAAC;AAEvD,SACE,4CAAC,SAAI,WAAW,6BAA6B,aAC3C;AAAA,IAAC;AAAA;AAAA,MACE,GAAG;AAAA,MACJ,OAAM;AAAA,MACN,SAAS;AAAA,QACP,SAAS;AAAA,UACP,SAAS;AAAA,UACT,UAAU;AAAA,QACZ;AAAA,QACA,UAAU;AAAA,QACV,qBAAqB;AAAA,QACrB,sBAAsB;AAAA,QACtB,iBAAiB;AAAA,QACjB,sBAAsB;AAAA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ACP,MAAM,sBAAM,cAAc,WAAW,OAAO;AAAA,QAC9C,CAAC;AACD;AAAA,MACF;AAEA,WAAK,SAAS;AAAA,QACZ,OAAO,IAAI,MAAM,mBAAmB;AAAA,QACpC,MAAM;AAAA,MACR,CAAC;AAAA,IACH,SAAS,GAAP;AAEA,UAAI,eAAe,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,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) {\n // ignore\n }\n await loadScript(babelUrl);\n }\n return window.Babel;\n}\n\nexport { getBabel };\n"]}
|
package/dist/web/esm/index.d.ts
CHANGED
|
@@ -26,7 +26,7 @@ declare class Runner extends Component<RunnerProps, RunnerState> {
|
|
|
26
26
|
timer: any;
|
|
27
27
|
constructor(props: RunnerProps);
|
|
28
28
|
waitCompile(targetCode: string): void;
|
|
29
|
-
doCompile(targetCode: string): void
|
|
29
|
+
doCompile(targetCode: string): Promise<void>;
|
|
30
30
|
componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void;
|
|
31
31
|
componentDidMount(): void;
|
|
32
32
|
componentDidUpdate(prevProps: RunnerProps): void;
|
package/dist/web/esm/index.js
CHANGED
|
@@ -4,10 +4,16 @@ import { default as default2, loader as loader2, EditorProps } from "@monaco-edi
|
|
|
4
4
|
// src/web/editor.tsx
|
|
5
5
|
import { jsx as _jsx } from "react/jsx-runtime";
|
|
6
6
|
import MonacoEditor, { loader } from "@monaco-editor/react";
|
|
7
|
+
|
|
8
|
+
// src/web/constant.ts
|
|
9
|
+
var DEFAULT_BABEL_URL = "https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.22.20/babel.min.js";
|
|
10
|
+
var DEFAULT_MONACO_URL = "https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.43.0/min/vs";
|
|
11
|
+
|
|
12
|
+
// src/web/editor.tsx
|
|
7
13
|
function initLoader() {
|
|
8
14
|
let loaderConfig = {
|
|
9
15
|
paths: {
|
|
10
|
-
vs:
|
|
16
|
+
vs: DEFAULT_MONACO_URL
|
|
11
17
|
}
|
|
12
18
|
};
|
|
13
19
|
try {
|
|
@@ -59,7 +65,6 @@ function Editor(props) {
|
|
|
59
65
|
|
|
60
66
|
// src/web/runner.tsx
|
|
61
67
|
import { jsx as _jsx2 } from "react/jsx-runtime";
|
|
62
|
-
import * as babel from "@babel/standalone";
|
|
63
68
|
import React, { Component } from "react";
|
|
64
69
|
|
|
65
70
|
// src/web/ast.ts
|
|
@@ -118,6 +123,39 @@ function createGetImport(name, getDefault) {
|
|
|
118
123
|
};
|
|
119
124
|
}
|
|
120
125
|
|
|
126
|
+
// src/web/utils.ts
|
|
127
|
+
var loadingMap = /* @__PURE__ */ new Map();
|
|
128
|
+
function loadScript(url) {
|
|
129
|
+
const exists = loadingMap.get(url);
|
|
130
|
+
if (exists) {
|
|
131
|
+
return exists;
|
|
132
|
+
}
|
|
133
|
+
const n = new Promise((resolve) => {
|
|
134
|
+
const e = document.createElement("script");
|
|
135
|
+
e.src = url;
|
|
136
|
+
e.onload = () => resolve();
|
|
137
|
+
document.body.appendChild(e);
|
|
138
|
+
});
|
|
139
|
+
loadingMap.set(url, n);
|
|
140
|
+
return n;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// src/web/babel.ts
|
|
144
|
+
async function getBabel() {
|
|
145
|
+
if (!window.Babel) {
|
|
146
|
+
let babelUrl = DEFAULT_BABEL_URL;
|
|
147
|
+
try {
|
|
148
|
+
const u = __PLAYGROUND_BABEL_URL__;
|
|
149
|
+
if (u) {
|
|
150
|
+
babelUrl = u;
|
|
151
|
+
}
|
|
152
|
+
} catch (e) {
|
|
153
|
+
}
|
|
154
|
+
await loadScript(babelUrl);
|
|
155
|
+
}
|
|
156
|
+
return window.Babel;
|
|
157
|
+
}
|
|
158
|
+
|
|
121
159
|
// src/web/runner.tsx
|
|
122
160
|
function _define_property(obj, key, value) {
|
|
123
161
|
if (key in obj) {
|
|
@@ -148,8 +186,9 @@ var Runner = class extends Component {
|
|
|
148
186
|
this.doCompile(targetCode);
|
|
149
187
|
}, 600);
|
|
150
188
|
}
|
|
151
|
-
doCompile(targetCode) {
|
|
189
|
+
async doCompile(targetCode) {
|
|
152
190
|
const { language, getImport } = this.props;
|
|
191
|
+
const babel = await getBabel();
|
|
153
192
|
try {
|
|
154
193
|
const presets = [
|
|
155
194
|
[
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"mappings":";AAAA,SACaA,WAAXC,UACUC,UAAVC,SACeC,mBACV;;;;ACHP,OAAOJ,gBACLG,cAEK;AASP,SAASE;AACP,MAAIC,eAAe;IACjBC,OAAO;MAAEC,IAAI;IAAgD;EAC/D;AAEA,MAAI;AACF,UAAMC,OAAOC,OAAOD,KAAKE;AAEzB,QAAIF,KAAKG,SAAS,GAAG;AACnBN,qBAAeK;IACjB;EACF,SAASE,GAAP;EAEF;AAEAV,SAAOW,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,Y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":["MonacoEditor","default","MonacoEditorLoader","loader","MonacoEditorProps","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","babel","React","Component","createVariableDeclaration","id","init","type","declarations","name","kind","createObjectPattern","names","properties","map","key","computed","method","shorthand","value","createGetImport","getDefault","callee","arguments","Boolean","Runner","getDerivedStateFromError","error","comp","waitCompile","targetCode","timer","clearTimeout","setTimeout","doCompile","language","getImport","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","createElement","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/runner.tsx","../../../src/web/home/runner/work/rspress/rspress/packages/plugin-playground/src/web/ast.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';\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: { vs: 'https://unpkg.com/monaco-editor@0.43.0/min/vs' },\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","import * as babel from '@babel/standalone';\nimport type { Node } from '@babel/types';\nimport React, { Component, HTMLAttributes } from 'react';\nimport {\n createGetImport,\n createObjectPattern,\n createVariableDeclaration,\n} from './ast';\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 doCompile(targetCode: string) {\n const { language, getImport } = this.props;\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"]}
|
|
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,IAAI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MACR;IACF;EACF;EAEA0C,kBAAkB3C,OAAc4C,WAA4B;AAC1DF,YAAQ1C,MAAMA;AACd0C,YAAQ1C,MAAM4C;EAChB;EAEAC,oBAAoB;AAClB,SAAKtC,UAAU,KAAKzE,MAAMgG,IAAI;EAChC;EAEAgB,mBAAmBC,WAAwB;AACzC,QAAIA,UAAUjB,SAAS,KAAKhG,MAAMgG,MAAM;AACtC,WAAK5B,YAAY,KAAKpE,MAAMgG,IAAI;IAClC;EACF;EAEAkB,SAAS;AACP,UAAM,EAAEhH,YAAY,IAAI8F,MAAMtB,UAAUC,WAAW,GAAGxE,SAAS,KAAKH;AACpE,UAAM,EAAEkE,OAAOC,KAAI,IAAK,KAAKgD;AAE7B,QAAIjD,OAAO;AACT,aACE,sBAAC9D;QAAIF,WAAW,6BAA6BA;QAAc,GAAGC;kBAC5D,sBAACiH;UAAKC,OAAO;YAAEC,OAAO;UAAM;oBAAIpD,MAAMqD;;;IAG5C;AAEA,WACE,sBAACnH;MAAIF,WAAW,6BAA6BA;MAAc,GAAGC;gBAC3DgE;;EAGP;EA1JAqD,YAAYxH,OAAoB;AAC9B,UAAMA;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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rspress/plugin-playground",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "A plugin for rspress to preview the code block in markdown/mdx file.",
|
|
5
5
|
"bugs": "https://github.com/web-infra-dev/rspress/issues",
|
|
6
6
|
"repository": {
|
|
@@ -32,13 +32,12 @@
|
|
|
32
32
|
"dist/"
|
|
33
33
|
],
|
|
34
34
|
"dependencies": {
|
|
35
|
-
"@babel/standalone": "^7.22.17",
|
|
36
35
|
"@mdx-js/mdx": "2.2.1",
|
|
37
|
-
"@modern-js/utils": "2.
|
|
36
|
+
"@modern-js/utils": "2.35.1",
|
|
38
37
|
"@monaco-editor/react": "~4.4.6",
|
|
39
38
|
"@oxidation-compiler/napi": "^0.1.0",
|
|
40
39
|
"remark-gfm": "3.0.1",
|
|
41
|
-
"@rspress/shared": "0.
|
|
40
|
+
"@rspress/shared": "0.1.1"
|
|
42
41
|
},
|
|
43
42
|
"devDependencies": {
|
|
44
43
|
"@babel/types": "^7.22.17",
|
|
@@ -60,7 +59,7 @@
|
|
|
60
59
|
"unist-util-visit": "^4.1.1"
|
|
61
60
|
},
|
|
62
61
|
"peerDependencies": {
|
|
63
|
-
"@rspress/core": "
|
|
62
|
+
"@rspress/core": "*",
|
|
64
63
|
"react": ">=17",
|
|
65
64
|
"react-router-dom": "^6.8.1"
|
|
66
65
|
},
|