@rspress/plugin-playground 0.0.0-nightly-20230919160314

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.
@@ -0,0 +1,297 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+
29
+ // src/web/index.ts
30
+ var web_exports = {};
31
+ __export(web_exports, {
32
+ Editor: () => Editor,
33
+ MonacoEditor: () => import_react3.default,
34
+ MonacoEditorLoader: () => import_react3.loader,
35
+ MonacoEditorProps: () => import_react3.EditorProps,
36
+ Runner: () => Runner
37
+ });
38
+ module.exports = __toCommonJS(web_exports);
39
+ var import_react3 = __toESM(require("@monaco-editor/react"));
40
+
41
+ // src/web/editor.tsx
42
+ var import_react = __toESM(require("@monaco-editor/react"));
43
+ var import_jsx_runtime = require("react/jsx-runtime");
44
+ function initLoader() {
45
+ let loaderConfig = {
46
+ paths: { vs: "https://unpkg.com/monaco-editor@0.43.0/min/vs" }
47
+ };
48
+ try {
49
+ const keys = Object.keys(__PLAYGROUND_MONACO_LOADER__);
50
+ if (keys.length > 0) {
51
+ loaderConfig = __PLAYGROUND_MONACO_LOADER__;
52
+ }
53
+ } catch (e) {
54
+ }
55
+ import_react.loader.config(loaderConfig);
56
+ }
57
+ initLoader();
58
+ function getMonacoOptions() {
59
+ try {
60
+ return __PLAYGROUND_MONACO_OPTIONS__;
61
+ } catch (e) {
62
+ }
63
+ return {};
64
+ }
65
+ function Editor(props) {
66
+ const { options, className = "", ...rest } = props || {};
67
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: `rspress-playground-editor ${className}`, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
68
+ import_react.default,
69
+ {
70
+ ...rest,
71
+ theme: "light",
72
+ options: {
73
+ minimap: {
74
+ enabled: true,
75
+ autohide: true
76
+ },
77
+ fontSize: 14,
78
+ lineNumbersMinChars: 7,
79
+ scrollBeyondLastLine: false,
80
+ automaticLayout: true,
81
+ wordBasedSuggestions: true,
82
+ quickSuggestions: true,
83
+ scrollbar: {
84
+ verticalScrollbarSize: 8,
85
+ horizontalScrollbarSize: 8
86
+ },
87
+ scrollPredominantAxis: false,
88
+ ...getMonacoOptions(),
89
+ ...options
90
+ }
91
+ }
92
+ ) });
93
+ }
94
+
95
+ // src/web/runner.tsx
96
+ var babel = __toESM(require("@babel/standalone"));
97
+ var import_react2 = __toESM(require("react"));
98
+
99
+ // src/web/ast.ts
100
+ function createVariableDeclaration(id, init) {
101
+ return {
102
+ type: "VariableDeclaration",
103
+ declarations: [
104
+ {
105
+ type: "VariableDeclarator",
106
+ id: typeof id === "string" ? {
107
+ type: "Identifier",
108
+ name: id
109
+ } : id,
110
+ init
111
+ }
112
+ ],
113
+ kind: "const"
114
+ };
115
+ }
116
+ function createObjectPattern(names) {
117
+ return {
118
+ type: "ObjectPattern",
119
+ properties: names.map((name) => ({
120
+ type: "ObjectProperty",
121
+ key: {
122
+ type: "Identifier",
123
+ name
124
+ },
125
+ computed: false,
126
+ method: false,
127
+ shorthand: true,
128
+ value: {
129
+ type: "Identifier",
130
+ name
131
+ }
132
+ }))
133
+ };
134
+ }
135
+ function createGetImport(name, getDefault) {
136
+ return {
137
+ type: "CallExpression",
138
+ callee: {
139
+ type: "Identifier",
140
+ name: "__get_import"
141
+ },
142
+ arguments: [
143
+ {
144
+ type: "StringLiteral",
145
+ value: name
146
+ },
147
+ {
148
+ type: "BooleanLiteral",
149
+ value: Boolean(getDefault)
150
+ }
151
+ ]
152
+ };
153
+ }
154
+
155
+ // src/web/runner.tsx
156
+ var import_jsx_runtime2 = require("react/jsx-runtime");
157
+ var Runner = class extends import_react2.Component {
158
+ constructor(props) {
159
+ super(props);
160
+ this.state = {
161
+ error: void 0,
162
+ comp: null
163
+ };
164
+ this.doCompile = this.doCompile.bind(this);
165
+ this.waitCompile = this.waitCompile.bind(this);
166
+ }
167
+ static getDerivedStateFromError(error) {
168
+ return {
169
+ error,
170
+ comp: null
171
+ };
172
+ }
173
+ waitCompile(targetCode) {
174
+ if (this.timer) {
175
+ clearTimeout(this.timer);
176
+ }
177
+ this.timer = setTimeout(() => {
178
+ this.timer = null;
179
+ this.doCompile(targetCode);
180
+ }, 600);
181
+ }
182
+ doCompile(targetCode) {
183
+ const { language, getImport } = this.props;
184
+ try {
185
+ const presets = [
186
+ [babel.availablePresets.react],
187
+ [babel.availablePresets.env, { modules: "commonjs" }]
188
+ ];
189
+ if (language === "tsx" || language === "ts") {
190
+ presets.unshift([
191
+ babel.availablePresets.typescript,
192
+ {
193
+ allExtensions: true,
194
+ isTSX: language === "tsx"
195
+ }
196
+ ]);
197
+ }
198
+ const result = babel.transform(targetCode, {
199
+ sourceType: "module",
200
+ presets,
201
+ plugins: [
202
+ {
203
+ visitor: {
204
+ ImportDeclaration(path) {
205
+ const pkg = path.node.source.value;
206
+ const code = [];
207
+ for (const specifier of path.node.specifiers) {
208
+ if (specifier.type === "ImportDefaultSpecifier") {
209
+ code.push(
210
+ createVariableDeclaration(
211
+ specifier.local.name,
212
+ createGetImport(pkg, true)
213
+ )
214
+ );
215
+ }
216
+ if (specifier.type === "ImportNamespaceSpecifier") {
217
+ code.push(
218
+ createVariableDeclaration(
219
+ specifier.local.name,
220
+ createGetImport(pkg)
221
+ )
222
+ );
223
+ }
224
+ if (specifier.type === "ImportSpecifier") {
225
+ code.push(
226
+ createVariableDeclaration(
227
+ createObjectPattern([specifier.local.name]),
228
+ createGetImport(pkg)
229
+ )
230
+ );
231
+ }
232
+ }
233
+ path.replaceWithMultiple(code);
234
+ }
235
+ }
236
+ }
237
+ ]
238
+ });
239
+ if (targetCode !== this.props.code || !result || !result.code) {
240
+ return;
241
+ }
242
+ const runExports = {};
243
+ const func = new Function("__get_import", "exports", result.code);
244
+ func(getImport, runExports);
245
+ if (runExports.default) {
246
+ this.setState({
247
+ error: void 0,
248
+ comp: import_react2.default.createElement(runExports.default)
249
+ });
250
+ return;
251
+ }
252
+ this.setState({
253
+ error: new Error("No default export"),
254
+ comp: null
255
+ });
256
+ } catch (e) {
257
+ if (targetCode !== this.props.code) {
258
+ return;
259
+ }
260
+ console.error(e);
261
+ this.setState({
262
+ error: e,
263
+ comp: null
264
+ });
265
+ }
266
+ }
267
+ componentDidCatch(error, errorInfo) {
268
+ console.error(error);
269
+ console.error(errorInfo);
270
+ }
271
+ componentDidMount() {
272
+ this.doCompile(this.props.code);
273
+ }
274
+ componentDidUpdate(prevProps) {
275
+ if (prevProps.code !== this.props.code) {
276
+ this.waitCompile(this.props.code);
277
+ }
278
+ }
279
+ render() {
280
+ const { className = "", code, language, getImport, ...rest } = this.props;
281
+ const { error, comp } = this.state;
282
+ if (error) {
283
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { className: `rspress-playground-runner ${className}`, ...rest, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { style: { color: "red" }, children: error.message }) });
284
+ }
285
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { className: `rspress-playground-runner ${className}`, ...rest, children: comp });
286
+ }
287
+ };
288
+ // Annotate the CommonJS export names for ESM import in node:
289
+ 0 && (module.exports = {
290
+ Editor,
291
+ MonacoEditor,
292
+ MonacoEditorLoader,
293
+ MonacoEditorProps,
294
+ Runner
295
+ });
296
+
297
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAIO;;;ACHP,mBAGO;AA4CD;AAnCN,SAAS,aAAa;AACpB,MAAI,eAAe;AAAA,IACjB,OAAO,EAAE,IAAI,gDAAgD;AAAA,EAC/D;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,iBAAi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AK,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/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"]}
@@ -0,0 +1,36 @@
1
+ import { EditorProps as EditorProps$1 } from '@monaco-editor/react';
2
+ export { default as MonacoEditor, loader as MonacoEditorLoader, EditorProps as MonacoEditorProps } from '@monaco-editor/react';
3
+ import React, { Component, HTMLAttributes } from 'react';
4
+
5
+ declare global {
6
+ const __PLAYGROUND_MONACO_LOADER__: any;
7
+ const __PLAYGROUND_MONACO_OPTIONS__: any;
8
+ }
9
+ type EditorProps = Partial<EditorProps$1>;
10
+ declare function Editor(props: EditorProps): JSX.Element;
11
+
12
+ interface RunnerProps extends HTMLAttributes<HTMLDivElement> {
13
+ code: string;
14
+ language: string;
15
+ getImport: (name: string, getDefault?: boolean) => void;
16
+ }
17
+ interface RunnerState {
18
+ error?: Error;
19
+ comp: any;
20
+ }
21
+ declare class Runner extends Component<RunnerProps, RunnerState> {
22
+ static getDerivedStateFromError(error: Error): {
23
+ error: Error;
24
+ comp: null;
25
+ };
26
+ timer: any;
27
+ constructor(props: RunnerProps);
28
+ waitCompile(targetCode: string): void;
29
+ doCompile(targetCode: string): void;
30
+ componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void;
31
+ componentDidMount(): void;
32
+ componentDidUpdate(prevProps: RunnerProps): void;
33
+ render(): JSX.Element;
34
+ }
35
+
36
+ export { Editor, Runner };
@@ -0,0 +1,282 @@
1
+ // src/web/index.ts
2
+ import { default as default2, loader as loader2, EditorProps } from "@monaco-editor/react";
3
+
4
+ // src/web/editor.tsx
5
+ import { jsx as _jsx } from "react/jsx-runtime";
6
+ import MonacoEditor, { loader } from "@monaco-editor/react";
7
+ function initLoader() {
8
+ let loaderConfig = {
9
+ paths: {
10
+ vs: "https://unpkg.com/monaco-editor@0.43.0/min/vs"
11
+ }
12
+ };
13
+ try {
14
+ const keys = Object.keys(__PLAYGROUND_MONACO_LOADER__);
15
+ if (keys.length > 0) {
16
+ loaderConfig = __PLAYGROUND_MONACO_LOADER__;
17
+ }
18
+ } catch (e) {
19
+ }
20
+ loader.config(loaderConfig);
21
+ }
22
+ initLoader();
23
+ function getMonacoOptions() {
24
+ try {
25
+ return __PLAYGROUND_MONACO_OPTIONS__;
26
+ } catch (e) {
27
+ }
28
+ return {};
29
+ }
30
+ function Editor(props) {
31
+ const { options, className = "", ...rest } = props || {};
32
+ return /* @__PURE__ */ _jsx("div", {
33
+ className: `rspress-playground-editor ${className}`,
34
+ children: /* @__PURE__ */ _jsx(MonacoEditor, {
35
+ ...rest,
36
+ theme: "light",
37
+ options: {
38
+ minimap: {
39
+ enabled: true,
40
+ autohide: true
41
+ },
42
+ fontSize: 14,
43
+ lineNumbersMinChars: 7,
44
+ scrollBeyondLastLine: false,
45
+ automaticLayout: true,
46
+ wordBasedSuggestions: true,
47
+ quickSuggestions: true,
48
+ scrollbar: {
49
+ verticalScrollbarSize: 8,
50
+ horizontalScrollbarSize: 8
51
+ },
52
+ scrollPredominantAxis: false,
53
+ ...getMonacoOptions(),
54
+ ...options
55
+ }
56
+ })
57
+ });
58
+ }
59
+
60
+ // src/web/runner.tsx
61
+ import { jsx as _jsx2 } from "react/jsx-runtime";
62
+ import * as babel from "@babel/standalone";
63
+ import React, { Component } from "react";
64
+
65
+ // src/web/ast.ts
66
+ function createVariableDeclaration(id, init) {
67
+ return {
68
+ type: "VariableDeclaration",
69
+ declarations: [
70
+ {
71
+ type: "VariableDeclarator",
72
+ id: typeof id === "string" ? {
73
+ type: "Identifier",
74
+ name: id
75
+ } : id,
76
+ init
77
+ }
78
+ ],
79
+ kind: "const"
80
+ };
81
+ }
82
+ function createObjectPattern(names) {
83
+ return {
84
+ type: "ObjectPattern",
85
+ properties: names.map((name) => ({
86
+ type: "ObjectProperty",
87
+ key: {
88
+ type: "Identifier",
89
+ name
90
+ },
91
+ computed: false,
92
+ method: false,
93
+ shorthand: true,
94
+ value: {
95
+ type: "Identifier",
96
+ name
97
+ }
98
+ }))
99
+ };
100
+ }
101
+ function createGetImport(name, getDefault) {
102
+ return {
103
+ type: "CallExpression",
104
+ callee: {
105
+ type: "Identifier",
106
+ name: "__get_import"
107
+ },
108
+ arguments: [
109
+ {
110
+ type: "StringLiteral",
111
+ value: name
112
+ },
113
+ {
114
+ type: "BooleanLiteral",
115
+ value: Boolean(getDefault)
116
+ }
117
+ ]
118
+ };
119
+ }
120
+
121
+ // src/web/runner.tsx
122
+ function _define_property(obj, key, value) {
123
+ if (key in obj) {
124
+ Object.defineProperty(obj, key, {
125
+ value,
126
+ enumerable: true,
127
+ configurable: true,
128
+ writable: true
129
+ });
130
+ } else {
131
+ obj[key] = value;
132
+ }
133
+ return obj;
134
+ }
135
+ var Runner = class extends Component {
136
+ static getDerivedStateFromError(error) {
137
+ return {
138
+ error,
139
+ comp: null
140
+ };
141
+ }
142
+ waitCompile(targetCode) {
143
+ if (this.timer) {
144
+ clearTimeout(this.timer);
145
+ }
146
+ this.timer = setTimeout(() => {
147
+ this.timer = null;
148
+ this.doCompile(targetCode);
149
+ }, 600);
150
+ }
151
+ doCompile(targetCode) {
152
+ const { language, getImport } = this.props;
153
+ try {
154
+ const presets = [
155
+ [
156
+ babel.availablePresets.react
157
+ ],
158
+ [
159
+ babel.availablePresets.env,
160
+ {
161
+ modules: "commonjs"
162
+ }
163
+ ]
164
+ ];
165
+ if (language === "tsx" || language === "ts") {
166
+ presets.unshift([
167
+ babel.availablePresets.typescript,
168
+ {
169
+ allExtensions: true,
170
+ isTSX: language === "tsx"
171
+ }
172
+ ]);
173
+ }
174
+ const result = babel.transform(targetCode, {
175
+ sourceType: "module",
176
+ presets,
177
+ plugins: [
178
+ {
179
+ visitor: {
180
+ ImportDeclaration(path) {
181
+ const pkg = path.node.source.value;
182
+ const code = [];
183
+ for (const specifier of path.node.specifiers) {
184
+ if (specifier.type === "ImportDefaultSpecifier") {
185
+ code.push(createVariableDeclaration(specifier.local.name, createGetImport(pkg, true)));
186
+ }
187
+ if (specifier.type === "ImportNamespaceSpecifier") {
188
+ code.push(createVariableDeclaration(specifier.local.name, createGetImport(pkg)));
189
+ }
190
+ if (specifier.type === "ImportSpecifier") {
191
+ code.push(createVariableDeclaration(createObjectPattern([
192
+ specifier.local.name
193
+ ]), createGetImport(pkg)));
194
+ }
195
+ }
196
+ path.replaceWithMultiple(code);
197
+ }
198
+ }
199
+ }
200
+ ]
201
+ });
202
+ if (targetCode !== this.props.code || !result || !result.code) {
203
+ return;
204
+ }
205
+ const runExports = {};
206
+ const func = new Function("__get_import", "exports", result.code);
207
+ func(getImport, runExports);
208
+ if (runExports.default) {
209
+ this.setState({
210
+ error: void 0,
211
+ comp: /* @__PURE__ */ React.createElement(runExports.default)
212
+ });
213
+ return;
214
+ }
215
+ this.setState({
216
+ error: new Error("No default export"),
217
+ comp: null
218
+ });
219
+ } catch (e) {
220
+ if (targetCode !== this.props.code) {
221
+ return;
222
+ }
223
+ console.error(e);
224
+ this.setState({
225
+ error: e,
226
+ comp: null
227
+ });
228
+ }
229
+ }
230
+ componentDidCatch(error, errorInfo) {
231
+ console.error(error);
232
+ console.error(errorInfo);
233
+ }
234
+ componentDidMount() {
235
+ this.doCompile(this.props.code);
236
+ }
237
+ componentDidUpdate(prevProps) {
238
+ if (prevProps.code !== this.props.code) {
239
+ this.waitCompile(this.props.code);
240
+ }
241
+ }
242
+ render() {
243
+ const { className = "", code, language, getImport, ...rest } = this.props;
244
+ const { error, comp } = this.state;
245
+ if (error) {
246
+ return /* @__PURE__ */ _jsx2("div", {
247
+ className: `rspress-playground-runner ${className}`,
248
+ ...rest,
249
+ children: /* @__PURE__ */ _jsx2("span", {
250
+ style: {
251
+ color: "red"
252
+ },
253
+ children: error.message
254
+ })
255
+ });
256
+ }
257
+ return /* @__PURE__ */ _jsx2("div", {
258
+ className: `rspress-playground-runner ${className}`,
259
+ ...rest,
260
+ children: comp
261
+ });
262
+ }
263
+ constructor(props) {
264
+ super(props);
265
+ _define_property(this, "timer", void 0);
266
+ this.state = {
267
+ error: void 0,
268
+ comp: null
269
+ };
270
+ this.doCompile = this.doCompile.bind(this);
271
+ this.waitCompile = this.waitCompile.bind(this);
272
+ }
273
+ };
274
+ export {
275
+ Editor,
276
+ default2 as MonacoEditor,
277
+ loader2 as MonacoEditorLoader,
278
+ EditorProps as MonacoEditorProps,
279
+ Runner
280
+ };
281
+
282
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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,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C/C;AAgJF;","names":["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"]}