princess-python-editor 0.1.0 → 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/index.es.js CHANGED
@@ -1,37 +1,37 @@
1
- var at = Object.defineProperty;
2
- var ot = (s, n, a) => n in s ? at(s, n, { enumerable: !0, configurable: !0, writable: !0, value: a }) : s[n] = a;
3
- var C = (s, n, a) => ot(s, typeof n != "symbol" ? n + "" : n, a);
4
- import { h as $e, defineComponent as it, ref as O, computed as W, onMounted as st, onBeforeUnmount as lt, watch as U, nextTick as Ie, openBlock as v, createElementBlock as b, normalizeStyle as Ne, normalizeClass as V, createVNode as $, unref as S, createElementVNode as p, createBlock as Pe, withDirectives as ut, vModelText as dt, toDisplayString as J, Fragment as se, renderList as le, createCommentVNode as G, withModifiers as ct, onScopeDispose as pt } from "vue";
5
- import { EditorState as ce, StateEffect as ft, StateField as ht, Compartment as X } from "@codemirror/state";
6
- import { EditorView as R, keymap as Re, lineNumbers as mt, highlightActiveLineGutter as yt, highlightActiveLine as vt, drawSelection as gt, placeholder as kt, Decoration as pe } from "@codemirror/view";
7
- import { oneDark as fe } from "@codemirror/theme-one-dark";
8
- import { linter as bt, forceLinting as wt } from "@codemirror/lint";
9
- import { autocompletion as xt } from "@codemirror/autocomplete";
10
- import { history as Et, defaultKeymap as St, historyKeymap as Ct, indentWithTab as Ot } from "@codemirror/commands";
11
- import { indentUnit as Lt } from "@codemirror/language";
12
- import { python as Te } from "@codemirror/lang-python";
13
- import { javascript as Ft } from "@codemirror/lang-javascript";
14
- import { json as Ht } from "@codemirror/lang-json";
15
- import { sql as Mt } from "@codemirror/lang-sql";
16
- const $t = "'JetBrains Mono', 'Fira Code', 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace", Ue = ft.define();
17
- function It(s, n) {
18
- const a = s.filter((o) => Number.isFinite(o) && o >= 1 && o <= n.lines).sort((o, i) => o - i);
19
- return pe.set(
20
- a.map((o) => pe.line({ class: "vpe-error-line" }).range(n.line(o).from))
1
+ var Ht = Object.defineProperty;
2
+ var Tt = (u, r, a) => r in u ? Ht(u, r, { enumerable: !0, configurable: !0, writable: !0, value: a }) : u[r] = a;
3
+ var L = (u, r, a) => Tt(u, typeof r != "symbol" ? r + "" : r, a);
4
+ import { h as Ke, defineComponent as Nt, ref as F, computed as ie, onMounted as jt, onBeforeUnmount as _t, watch as V, nextTick as Ae, openBlock as g, createElementBlock as v, normalizeStyle as qe, normalizeClass as B, createVNode as $, unref as S, createElementVNode as c, createBlock as We, withDirectives as Dt, vModelText as Ut, toDisplayString as W, Fragment as se, renderList as de, createCommentVNode as z, withModifiers as Vt, onScopeDispose as Bt } from "vue";
5
+ import { EditorState as Se, StateEffect as zt, StateField as Kt, Compartment as ce } from "@codemirror/state";
6
+ import { EditorView as K, keymap as Je, lineNumbers as At, highlightActiveLineGutter as qt, highlightActiveLine as Wt, drawSelection as Jt, placeholder as Zt, Decoration as Ee } from "@codemirror/view";
7
+ import { oneDark as Fe } from "@codemirror/theme-one-dark";
8
+ import { linter as Gt, forceLinting as Xt } from "@codemirror/lint";
9
+ import { autocompletion as Yt, closeBrackets as Qt, closeBracketsKeymap as en } from "@codemirror/autocomplete";
10
+ import { history as tn, defaultKeymap as nn, historyKeymap as rn, indentWithTab as an } from "@codemirror/commands";
11
+ import { indentUnit as sn, bracketMatching as on } from "@codemirror/language";
12
+ import { python as Qe } from "@codemirror/lang-python";
13
+ import { javascript as ln } from "@codemirror/lang-javascript";
14
+ import { json as un } from "@codemirror/lang-json";
15
+ import { sql as dn } from "@codemirror/lang-sql";
16
+ const cn = "'JetBrains Mono', 'Fira Code', 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace", et = zt.define();
17
+ function pn(u, r) {
18
+ const a = u.filter((i) => Number.isFinite(i) && i >= 1 && i <= r.lines).sort((i, s) => i - s);
19
+ return Ee.set(
20
+ a.map((i) => Ee.line({ class: "vpe-error-line" }).range(r.line(i).from))
21
21
  );
22
22
  }
23
- const Nt = ht.define({
24
- create: () => pe.none,
25
- update: (s, n) => {
26
- let a = s;
27
- for (const o of n.effects)
28
- o.is(Ue) && (a = It(o.value, n.state.doc));
29
- return n.docChanged && (a = a.map(n.changes)), a;
23
+ const fn = Kt.define({
24
+ create: () => Ee.none,
25
+ update: (u, r) => {
26
+ let a = u;
27
+ for (const i of r.effects)
28
+ i.is(et) && (a = pn(i.value, r.state.doc));
29
+ return r.docChanged && (a = a.map(r.changes)), a;
30
30
  },
31
- provide: (s) => R.decorations.from(s)
32
- }), Pt = R.theme({
31
+ provide: (u) => K.decorations.from(u)
32
+ }), hn = K.theme({
33
33
  "&": { height: "100%", fontSize: "13px" },
34
- ".cm-scroller": { fontFamily: $t, lineHeight: "1.65" },
34
+ ".cm-scroller": { fontFamily: cn, lineHeight: "1.65" },
35
35
  ".cm-content": { padding: "10px 0 14px" },
36
36
  ".cm-gutters": {
37
37
  borderRight: "none",
@@ -41,66 +41,68 @@ const Nt = ht.define({
41
41
  },
42
42
  "&.cm-focused": { outline: "none" }
43
43
  });
44
- function Rt(s, n) {
45
- const a = R.updateListener.of((k) => {
46
- k.docChanged && n.onDocChange(k.state.doc.toString());
47
- }), o = Re.of([
44
+ function mn(u, r) {
45
+ const a = K.updateListener.of((P) => {
46
+ P.docChanged && r.onDocChange(P.state.doc.toString());
47
+ }), i = Je.of([
48
48
  {
49
49
  key: "Mod-Enter",
50
50
  preventDefault: !0,
51
- run: () => (n.onRunShortcut(), !0)
51
+ run: () => (r.onRunShortcut(), !0)
52
52
  }
53
- ]), i = ce.create({
54
- doc: n.value,
53
+ ]), s = Se.create({
54
+ doc: r.value,
55
55
  extensions: [
56
- Pt,
57
- mt(),
58
- yt(),
59
- vt(),
60
- gt(),
61
- Et(),
62
- Lt.of(" "),
63
- n.language ?? Te(),
64
- xt(),
65
- R.lineWrapping,
66
- kt(n.placeholderText),
67
- Nt,
68
- o,
69
- Re.of([...St, ...Ct, Ot]),
70
- ...n.dark ? [fe] : [],
71
- ...n.extensions,
56
+ hn,
57
+ At(),
58
+ qt(),
59
+ Wt(),
60
+ Jt(),
61
+ tn(),
62
+ sn.of(" "),
63
+ r.language ?? Qe(),
64
+ Yt(),
65
+ Qt(),
66
+ on(),
67
+ K.lineWrapping,
68
+ Zt(r.placeholderText),
69
+ fn,
70
+ i,
71
+ Je.of([...en, ...nn, ...rn, an]),
72
+ ...r.dark ? [Fe] : [],
73
+ ...r.extensions,
72
74
  a
73
75
  ]
74
76
  });
75
- return new R({ state: i, parent: s });
77
+ return new K({ state: s, parent: u });
76
78
  }
77
- function jt(s, n = 600) {
78
- return bt(
79
+ function yn(u, r = 600) {
80
+ return Gt(
79
81
  async (a) => {
80
- const o = a.state.doc.toString();
81
- if (!o.trim()) return [];
82
- let i = null;
82
+ const i = a.state.doc.toString();
83
+ if (!i.trim()) return [];
84
+ let s = null;
83
85
  try {
84
- i = await s.checkSyntax(o);
86
+ s = await u.checkSyntax(i);
85
87
  } catch {
86
88
  return [];
87
89
  }
88
- if (!i) return [];
89
- const k = Math.min(Math.max(Math.round(i.line) || 1, 1), a.state.doc.lines), w = a.state.doc.line(k), L = Math.min(Math.max(Math.round(i.column) || 1, 1), w.length + 1), I = w.from + L - 1, x = Math.min(I + 1, w.to);
90
+ if (!s) return [];
91
+ const P = Math.min(Math.max(Math.round(s.line) || 1, 1), a.state.doc.lines), w = a.state.doc.line(P), I = Math.min(Math.max(Math.round(s.column) || 1, 1), w.length + 1), H = w.from + I - 1, C = Math.min(H + 1, w.to);
90
92
  return [
91
93
  {
92
- from: I,
93
- to: x,
94
+ from: H,
95
+ to: C,
94
96
  severity: "error",
95
- message: i.message,
97
+ message: s.message,
96
98
  source: "python-syntax"
97
99
  }
98
100
  ];
99
101
  },
100
- { delay: n }
102
+ { delay: r }
101
103
  );
102
104
  }
103
- const Tt = [
105
+ const gn = [
104
106
  "import ast, json",
105
107
  "def _pye_check(src):",
106
108
  " try:",
@@ -109,11 +111,11 @@ const Tt = [
109
111
  " except SyntaxError as e:",
110
112
  " return json.dumps({'ok': False, 'line': int(e.lineno or 1), 'column': int(e.offset or 1), 'message': str(e.msg or 'invalid syntax')})"
111
113
  ];
112
- function Ut(s) {
113
- const n = s.endsWith("/") ? s : s + "/";
114
+ function vn(u) {
115
+ const r = u.endsWith("/") ? u : u + "/";
114
116
  return `
115
- var INDEX_URL = ${JSON.stringify(n)};
116
- var CHECK_SOURCE = ${JSON.stringify(Tt.join(`
117
+ var INDEX_URL = ${JSON.stringify(r)};
118
+ var CHECK_SOURCE = ${JSON.stringify(gn.join(`
117
119
  `))};
118
120
  var pyodide = null;
119
121
  var checkFn = null;
@@ -135,6 +137,85 @@ function parseError(e) {
135
137
  return { type: type, message: detail, line: line, traceback: msg };
136
138
  }
137
139
 
140
+ function fsError(e) {
141
+ return {
142
+ type: String((e && e.name) || 'OSError'),
143
+ message: String((e && e.message) || e),
144
+ traceback: ''
145
+ };
146
+ }
147
+
148
+ /** 将相对路径解析为虚拟文件系统中的绝对路径(默认基于 /home/pyodide) */
149
+ function normPath(p) {
150
+ var raw = String(p == null ? '' : p);
151
+ if (!raw) return pyodide.FS.cwd();
152
+ var full = raw.charAt(0) === '/' ? raw : pyodide.FS.cwd() + '/' + raw;
153
+ var parts = full.split('/');
154
+ var out = [];
155
+ for (var i = 0; i < parts.length; i++) {
156
+ var seg = parts[i];
157
+ if (!seg || seg === '.') continue;
158
+ if (seg === '..') {
159
+ if (out.length) out.pop();
160
+ continue;
161
+ }
162
+ out.push(seg);
163
+ }
164
+ return '/' + out.join('/');
165
+ }
166
+
167
+ /** 将预置文本按行切分,逐行提供给 input();text 为 null 时立即 EOF */
168
+ function makeStdin(text) {
169
+ var lines = null;
170
+ if (text !== undefined && text !== null) {
171
+ lines = String(text).split(/\\r\\n|\\n|\\r/);
172
+ if (lines.length && lines[lines.length - 1] === '') lines.pop();
173
+ }
174
+ var index = 0;
175
+ return function () {
176
+ if (!lines || index >= lines.length) return null;
177
+ var line = lines[index];
178
+ index += 1;
179
+ return line + '\\n';
180
+ };
181
+ }
182
+
183
+ /** 递归列出虚拟文件;跳过缓存目录并限制深度与条目数,避免大目录阻塞 */
184
+ function listFs(path, recursive) {
185
+ var entries = [];
186
+ function walk(dir, depth) {
187
+ var names = pyodide.FS.readdir(dir);
188
+ for (var i = 0; i < names.length; i++) {
189
+ var name = names[i];
190
+ if (name === '.' || name === '..') continue;
191
+ if (name === '__pycache__' || name === '.cache') continue;
192
+ var full = dir === '/' ? '/' + name : dir + '/' + name;
193
+ var stat;
194
+ try {
195
+ stat = pyodide.FS.stat(full);
196
+ } catch (e) {
197
+ continue;
198
+ }
199
+ var isDir = pyodide.FS.isDir(stat.mode);
200
+ entries.push({
201
+ name: name,
202
+ path: full,
203
+ isDirectory: isDir,
204
+ size: isDir ? 0 : stat.size
205
+ });
206
+ if (isDir && recursive && depth < 4 && entries.length < 500) {
207
+ walk(full, depth + 1);
208
+ }
209
+ }
210
+ }
211
+ walk(path, 0);
212
+ entries.sort(function (a, b) {
213
+ if (a.isDirectory !== b.isDirectory) return a.isDirectory ? -1 : 1;
214
+ return a.path < b.path ? -1 : a.path > b.path ? 1 : 0;
215
+ });
216
+ return entries;
217
+ }
218
+
138
219
  async function init() {
139
220
  try {
140
221
  self.importScripts(INDEX_URL + 'pyodide.js');
@@ -167,6 +248,7 @@ self.onmessage = async function (ev) {
167
248
  return;
168
249
  }
169
250
  try {
251
+ pyodide.setStdin({ stdin: makeStdin(msg.stdin) });
170
252
  var result = await pyodide.runPythonAsync(msg.code);
171
253
  var value;
172
254
  if (result !== undefined && result !== null) {
@@ -209,99 +291,168 @@ self.onmessage = async function (ev) {
209
291
  }
210
292
  }
211
293
  currentId = 0;
294
+
295
+ } else if (msg.kind === 'fs-write') {
296
+ if (!pyodide) {
297
+ post({ kind: 'fs-written', id: msg.id, ok: false, error: { type: 'RuntimeError', message: 'Pyodide 未初始化', traceback: '' } });
298
+ return;
299
+ }
300
+ try {
301
+ var writePath = normPath(msg.path);
302
+ var slash = writePath.lastIndexOf('/');
303
+ var dir = slash <= 0 ? '/' : writePath.slice(0, slash);
304
+ try {
305
+ pyodide.FS.mkdirTree(dir);
306
+ } catch (e0) {
307
+ // 目录已存在时忽略
308
+ }
309
+ pyodide.FS.writeFile(writePath, String(msg.content == null ? '' : msg.content), { encoding: 'utf8' });
310
+ post({ kind: 'fs-written', id: msg.id, ok: true, path: writePath });
311
+ } catch (e) {
312
+ post({ kind: 'fs-written', id: msg.id, ok: false, error: fsError(e) });
313
+ }
314
+
315
+ } else if (msg.kind === 'fs-read') {
316
+ if (!pyodide) {
317
+ post({ kind: 'fs-read', id: msg.id, ok: false, error: { type: 'RuntimeError', message: 'Pyodide 未初始化', traceback: '' } });
318
+ return;
319
+ }
320
+ try {
321
+ var readPath = normPath(msg.path);
322
+ var content = pyodide.FS.readFile(readPath, { encoding: 'utf8' });
323
+ post({ kind: 'fs-read', id: msg.id, ok: true, path: readPath, content: content });
324
+ } catch (e) {
325
+ post({ kind: 'fs-read', id: msg.id, ok: false, error: fsError(e) });
326
+ }
327
+
328
+ } else if (msg.kind === 'fs-list') {
329
+ if (!pyodide) {
330
+ post({ kind: 'fs-list', id: msg.id, ok: false, error: { type: 'RuntimeError', message: 'Pyodide 未初始化', traceback: '' } });
331
+ return;
332
+ }
333
+ try {
334
+ var listPath = normPath(msg.path);
335
+ var entries = listFs(listPath, msg.recursive !== false);
336
+ post({ kind: 'fs-list', id: msg.id, ok: true, path: listPath, entries: entries });
337
+ } catch (e) {
338
+ post({ kind: 'fs-list', id: msg.id, ok: false, error: fsError(e) });
339
+ }
212
340
  }
213
341
  };
214
342
  `;
215
343
  }
216
- const Ve = "https://cdn.jsdelivr.net/pyodide/v0.27.2/full/";
217
- class Vt {
218
- constructor(n = {}) {
219
- C(this, "status", "idle");
220
- C(this, "version", "");
221
- C(this, "pyodideUrl");
222
- C(this, "worker", null);
223
- C(this, "pending", /* @__PURE__ */ new Map());
224
- C(this, "seq", 1);
225
- C(this, "chain", Promise.resolve());
344
+ const tt = "https://cdn.jsdelivr.net/pyodide/v0.27.2/full/";
345
+ class kn {
346
+ constructor(r = {}) {
347
+ L(this, "status", "idle");
348
+ L(this, "version", "");
349
+ L(this, "pyodideUrl");
350
+ L(this, "worker", null);
351
+ L(this, "pending", /* @__PURE__ */ new Map());
352
+ L(this, "seq", 1);
353
+ L(this, "chain", Promise.resolve());
226
354
  /** Worker 生命周期代数:interrupt 后递增,用于废弃旧的 waitReady 等待 */
227
- C(this, "generation", 0);
228
- C(this, "statusHandlers", /* @__PURE__ */ new Set());
229
- C(this, "outputHandlers", /* @__PURE__ */ new Set());
230
- C(this, "initErrorHandlers", /* @__PURE__ */ new Set());
231
- this.pyodideUrl = n.pyodideUrl || Ve;
355
+ L(this, "generation", 0);
356
+ L(this, "statusHandlers", /* @__PURE__ */ new Set());
357
+ L(this, "outputHandlers", /* @__PURE__ */ new Set());
358
+ L(this, "initErrorHandlers", /* @__PURE__ */ new Set());
359
+ this.pyodideUrl = r.pyodideUrl || tt;
232
360
  }
233
- on(n, a) {
234
- if (n === "status") {
235
- const i = a;
236
- return this.statusHandlers.add(i), () => this.statusHandlers.delete(i);
361
+ on(r, a) {
362
+ if (r === "status") {
363
+ const s = a;
364
+ return this.statusHandlers.add(s), () => this.statusHandlers.delete(s);
237
365
  }
238
- if (n === "output") {
239
- const i = a;
240
- return this.outputHandlers.add(i), () => this.outputHandlers.delete(i);
366
+ if (r === "output") {
367
+ const s = a;
368
+ return this.outputHandlers.add(s), () => this.outputHandlers.delete(s);
241
369
  }
242
- const o = a;
243
- return this.initErrorHandlers.add(o), () => this.initErrorHandlers.delete(o);
370
+ const i = a;
371
+ return this.initErrorHandlers.add(i), () => this.initErrorHandlers.delete(i);
244
372
  }
245
373
  /** 预加载 Pyodide(返回 Promise,在就绪或失败时 settle) */
246
- waitReady(n = 18e4) {
374
+ waitReady(r = 18e4) {
247
375
  const a = this.generation;
248
- return this.ensureWorker(), this.status === "ready" || this.status === "running" ? Promise.resolve() : new Promise((o, i) => {
249
- let k = () => {
376
+ return this.ensureWorker(), this.status === "ready" || this.status === "running" ? Promise.resolve() : new Promise((i, s) => {
377
+ let P = () => {
250
378
  }, w = () => {
251
379
  };
252
- const L = () => {
253
- clearTimeout(I), k(), w();
254
- }, I = setTimeout(() => {
255
- L(), i(new Error("Pyodide 加载超时"));
256
- }, n);
257
- k = this.on("status", (x) => {
380
+ const I = () => {
381
+ clearTimeout(H), P(), w();
382
+ }, H = setTimeout(() => {
383
+ I(), s(new Error("Pyodide 加载超时"));
384
+ }, r);
385
+ P = this.on("status", (C) => {
258
386
  if (this.generation !== a) {
259
- L(), i(new Error("执行已被中断"));
387
+ I(), s(new Error("执行已被中断"));
260
388
  return;
261
389
  }
262
- x === "ready" && (L(), o());
263
- }), w = this.on("initError", (x) => {
264
- L(), i(new Error(x));
390
+ C === "ready" && (I(), i());
391
+ }), w = this.on("initError", (C) => {
392
+ I(), s(new Error(C));
265
393
  });
266
394
  });
267
395
  }
268
396
  /** 执行一段 Python 代码(支持顶层 await);运行器未就绪时先等待初始化完成 */
269
- async run(n, a) {
397
+ async run(r, a) {
270
398
  await this.waitReady();
271
- const o = performance.now();
399
+ const i = performance.now();
272
400
  this.setStatus("running");
273
- const i = await this.send(
274
- { kind: "run", id: this.seq++, code: n },
401
+ const s = await this.send(
402
+ { kind: "run", id: this.seq++, code: r, stdin: a == null ? void 0 : a.stdin },
275
403
  a == null ? void 0 : a.onOutput
276
404
  );
277
405
  return this.status === "running" && this.setStatus("ready"), {
278
- ok: i.ok,
279
- value: i.value,
280
- error: i.error,
281
- interrupted: i.interrupted,
282
- durationMs: performance.now() - o
406
+ ok: s.ok,
407
+ value: s.value,
408
+ error: s.error,
409
+ interrupted: s.interrupted,
410
+ durationMs: performance.now() - i
283
411
  };
284
412
  }
285
413
  /** 语法检查:仅在运行器就绪时可用,否则返回 null(静默跳过) */
286
- async checkSyntax(n) {
287
- if (this.status !== "ready" || !n.trim()) return null;
288
- const a = await this.send({ kind: "check", id: this.seq++, code: n });
414
+ async checkSyntax(r) {
415
+ if (this.status !== "ready" || !r.trim()) return null;
416
+ const a = await this.send({ kind: "check", id: this.seq++, code: r });
289
417
  return a.ok ? null : {
290
418
  line: a.line ?? 1,
291
419
  column: a.column ?? 1,
292
420
  message: a.message ?? "语法错误"
293
421
  };
294
422
  }
423
+ /** 写入虚拟文件系统(UTF-8 文本),相对路径基于当前工作目录 */
424
+ async writeFile(r, a) {
425
+ await this.waitReady();
426
+ const i = await this.send({ kind: "fs-write", id: this.seq++, path: r, content: a });
427
+ return { ok: i.ok, path: i.path, error: i.error };
428
+ }
429
+ /** 读取虚拟文件系统中的文本文件;二进制内容会返回失败 */
430
+ async readFile(r) {
431
+ await this.waitReady();
432
+ const a = await this.send({ kind: "fs-read", id: this.seq++, path: r });
433
+ return { ok: a.ok, path: a.path, content: a.content, error: a.error };
434
+ }
435
+ /** 列出虚拟文件系统目录(递归,跳过 __pycache__ / .cache) */
436
+ async listFiles(r = ".") {
437
+ await this.waitReady();
438
+ const a = await this.send({
439
+ kind: "fs-list",
440
+ id: this.seq++,
441
+ path: r,
442
+ recursive: !0
443
+ });
444
+ return { ok: a.ok, path: a.path, entries: a.entries, error: a.error };
445
+ }
295
446
  /** 安装第三方包:先尝试内置 wheel(loadPackage),失败后回退 micropip */
296
- async loadPackages(n, a) {
447
+ async loadPackages(r, a) {
297
448
  await this.waitReady();
298
- const o = performance.now();
449
+ const i = performance.now();
299
450
  this.setStatus("running");
300
- const i = await this.send(
301
- { kind: "install", id: this.seq++, packages: n },
451
+ const s = await this.send(
452
+ { kind: "install", id: this.seq++, packages: r },
302
453
  a == null ? void 0 : a.onOutput
303
454
  );
304
- return this.status === "running" && this.setStatus("ready"), { ok: i.ok, error: i.error, durationMs: performance.now() - o };
455
+ return this.status === "running" && this.setStatus("ready"), { ok: s.ok, error: s.error, durationMs: performance.now() - i };
305
456
  }
306
457
  /**
307
458
  * 中断当前执行:terminate Worker(Pyodide 无法真正中断同步计算),
@@ -310,102 +461,127 @@ class Vt {
310
461
  interrupt() {
311
462
  if (!this.worker) return;
312
463
  this.generation += 1, this.worker.terminate(), this.worker = null;
313
- const n = {
464
+ const r = {
314
465
  ok: !1,
315
466
  interrupted: !0,
316
467
  error: { type: "KeyboardInterrupt", message: "执行已被用户中断", traceback: "" }
317
468
  };
318
- this.pending.forEach((a) => a.resolve(n)), this.pending.clear(), this.chain = Promise.resolve(), this.setStatus("idle");
469
+ this.pending.forEach((a) => a.resolve(r)), this.pending.clear(), this.chain = Promise.resolve(), this.setStatus("idle");
319
470
  }
320
471
  ensureWorker() {
321
472
  if (this.worker) return this.worker;
322
- const n = new Blob([Ut(this.pyodideUrl)], { type: "text/javascript" }), a = new Worker(URL.createObjectURL(n));
323
- return a.onmessage = (o) => this.handleMessage(o.data), this.worker = a, this.setStatus("loading"), a;
473
+ const r = new Blob([vn(this.pyodideUrl)], { type: "text/javascript" }), a = new Worker(URL.createObjectURL(r));
474
+ return a.onmessage = (i) => this.handleMessage(i.data), this.worker = a, this.setStatus("loading"), a;
324
475
  }
325
- handleMessage(n) {
326
- switch (n.kind) {
476
+ handleMessage(r) {
477
+ switch (r.kind) {
327
478
  case "ready":
328
- this.version = n.version, this.setStatus("ready");
479
+ this.version = r.version, this.setStatus("ready");
329
480
  break;
330
481
  case "init-error":
331
- this.setStatus("idle"), this.initErrorHandlers.forEach((a) => a(n.message));
482
+ this.setStatus("idle"), this.initErrorHandlers.forEach((a) => a(r.message));
332
483
  break;
333
484
  case "output": {
334
- const a = n.runId ? this.pending.get(n.runId) : void 0;
335
- a != null && a.onOutput ? a.onOutput(n.stream, n.text) : this.outputHandlers.forEach((o) => o(n.stream, n.text));
485
+ const a = r.runId ? this.pending.get(r.runId) : void 0;
486
+ a != null && a.onOutput ? a.onOutput(r.stream, r.text) : this.outputHandlers.forEach((i) => i(r.stream, r.text));
336
487
  break;
337
488
  }
338
489
  case "result": {
339
- const a = this.pending.get(n.id);
340
- a && (this.pending.delete(n.id), a.resolve({ ok: n.ok, value: n.value, error: n.error }));
490
+ const a = this.pending.get(r.id);
491
+ a && (this.pending.delete(r.id), a.resolve({ ok: r.ok, value: r.value, error: r.error }));
341
492
  break;
342
493
  }
343
494
  case "checked": {
344
- const a = this.pending.get(n.id);
345
- a && (this.pending.delete(n.id), a.resolve({
346
- ok: n.ok,
347
- line: n.line,
348
- column: n.column,
349
- message: n.message
495
+ const a = this.pending.get(r.id);
496
+ a && (this.pending.delete(r.id), a.resolve({
497
+ ok: r.ok,
498
+ line: r.line,
499
+ column: r.column,
500
+ message: r.message
350
501
  }));
351
502
  break;
352
503
  }
353
504
  case "installed": {
354
- const a = this.pending.get(n.id);
355
- a && (this.pending.delete(n.id), a.resolve({ ok: n.ok, error: n.error }));
505
+ const a = this.pending.get(r.id);
506
+ a && (this.pending.delete(r.id), a.resolve({ ok: r.ok, error: r.error }));
507
+ break;
508
+ }
509
+ case "fs-written": {
510
+ const a = this.pending.get(r.id);
511
+ a && (this.pending.delete(r.id), a.resolve({ ok: r.ok, path: r.path, error: r.error }));
512
+ break;
513
+ }
514
+ case "fs-read": {
515
+ const a = this.pending.get(r.id);
516
+ a && (this.pending.delete(r.id), a.resolve({
517
+ ok: r.ok,
518
+ path: r.path,
519
+ content: r.content,
520
+ error: r.error
521
+ }));
522
+ break;
523
+ }
524
+ case "fs-list": {
525
+ const a = this.pending.get(r.id);
526
+ a && (this.pending.delete(r.id), a.resolve({
527
+ ok: r.ok,
528
+ path: r.path,
529
+ entries: r.entries,
530
+ error: r.error
531
+ }));
356
532
  break;
357
533
  }
358
534
  }
359
535
  }
360
- send(n, a) {
361
- const o = this.ensureWorker(), i = this.chain.then(
362
- () => new Promise((k) => {
363
- this.pending.set(n.id, { resolve: k, onOutput: a }), o.postMessage(n);
536
+ send(r, a) {
537
+ const i = this.ensureWorker(), s = this.chain.then(
538
+ () => new Promise((P) => {
539
+ this.pending.set(r.id, { resolve: P, onOutput: a }), i.postMessage(r);
364
540
  })
365
541
  );
366
- return this.chain = i.then(
542
+ return this.chain = s.then(
367
543
  () => {
368
544
  },
369
545
  () => {
370
546
  }
371
- ), i;
547
+ ), s;
372
548
  }
373
- setStatus(n) {
374
- this.status !== n && (this.status = n, this.statusHandlers.forEach((a) => a(n, this.version)));
549
+ setStatus(r) {
550
+ this.status !== r && (this.status = r, this.statusHandlers.forEach((a) => a(r, this.version)));
375
551
  }
376
552
  }
377
- let ue = null;
378
- function ze(s) {
379
- return ue ? s != null && s.pyodideUrl && s.pyodideUrl !== Ve && console.warn(
553
+ let be = null;
554
+ function nt(u) {
555
+ return be ? u != null && u.pyodideUrl && u.pyodideUrl !== tt && console.warn(
380
556
  "[princess-python-editor] Pyodide 运行器已初始化,后续传入的 pyodideUrl 将被忽略。"
381
- ) : ue = new Vt(s), ue;
557
+ ) : be = new kn(u), be;
382
558
  }
383
- const he = [
559
+ const fe = [
384
560
  { value: "python", label: "Python", extension: "py" },
385
561
  { value: "sql", label: "SQL", extension: "sql" },
386
562
  { value: "javascript", label: "JavaScript", extension: "js" },
387
563
  { value: "json", label: "JSON", extension: "json" }
388
564
  ];
389
- function Y(s) {
390
- return he.find((n) => n.value === s) ?? he[0];
565
+ function pe(u) {
566
+ return fe.find((r) => r.value === u) ?? fe[0];
391
567
  }
392
- function de(s) {
393
- switch (s) {
568
+ function we(u) {
569
+ switch (u) {
394
570
  case "sql":
395
- return Mt();
571
+ return dn();
396
572
  case "javascript":
397
- return Ft();
573
+ return ln();
398
574
  case "json":
399
- return Ht();
575
+ return un();
400
576
  case "python":
401
577
  default:
402
- return Te();
578
+ return Qe();
403
579
  }
404
580
  }
405
- function zt(s) {
406
- const n = s.lastIndexOf(".");
407
- if (n < 0) return "python";
408
- switch (s.slice(n + 1).toLowerCase()) {
581
+ function bn(u) {
582
+ const r = u.lastIndexOf(".");
583
+ if (r < 0) return "python";
584
+ switch (u.slice(r + 1).toLowerCase()) {
409
585
  case "sql":
410
586
  return "sql";
411
587
  case "js":
@@ -420,9 +596,9 @@ function zt(s) {
420
596
  return "python";
421
597
  }
422
598
  }
423
- function F(s) {
424
- const n = Array.isArray(s) ? s : [s];
425
- return () => $e(
599
+ function R(u) {
600
+ const r = Array.isArray(u) ? u : [u];
601
+ return () => Ke(
426
602
  "svg",
427
603
  {
428
604
  viewBox: "0 0 24 24",
@@ -431,33 +607,44 @@ function F(s) {
431
607
  fill: "currentColor",
432
608
  "aria-hidden": "true"
433
609
  },
434
- n.map((a) => $e("path", { d: a }))
610
+ r.map((a) => Ke("path", { d: a }))
435
611
  );
436
612
  }
437
- const Dt = F(
613
+ const wn = R(
438
614
  "M8 5.14v13.72a1 1 0 0 0 1.54.84l10.3-6.86a1 1 0 0 0 0-1.68L9.54 4.3A1 1 0 0 0 8 5.14Z"
439
- ), _t = F("M6 6h12v12H6Z"), je = F(
615
+ ), xn = R("M6 6h12v12H6Z"), Ze = R(
440
616
  "M9 3h6a1 1 0 0 1 1 1v1h4a1 1 0 1 1 0 2h-1.06l-.87 12.13A2 2 0 0 1 16.08 21H7.92a2 2 0 0 1-1.99-1.87L5.06 7H4a1 1 0 0 1 0-2h4V4a1 1 0 0 1 1-1Zm1 2h4V5h-4v0Zm-2.92 2h9.84l-.85 12.07a.5.5 0 0 1-.5.43H7.93a.5.5 0 0 1-.5-.43Z"
441
- ), Bt = F(
617
+ ), Sn = R(
442
618
  "M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm2 14h-3v3h-2v-3H8v-2h3v-3h2v3h3v2zm-3-7V3.5L18.5 9H13z"
443
- ), At = F(
619
+ ), En = R(
444
620
  "M10 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"
445
- ), qt = F(
621
+ ), Ge = R(
446
622
  "M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm2 16H8v-2h8v2zm0-4H8v-2h8v2zm-3-5V3.5L18.5 9H13z"
447
- ), Kt = F("M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"), Wt = F(
623
+ ), Xe = R("M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"), Fn = R(
448
624
  "M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"
449
- ), Zt = F("M9 16.17 4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"), Jt = F(
625
+ ), Pn = R("M9 16.17 4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"), Ye = R(
450
626
  "M18.3 5.71a1 1 0 0 0-1.41 0L12 10.59 7.11 5.7A1 1 0 0 0 5.7 7.11L10.59 12 5.7 16.89a1 1 0 1 0 1.41 1.41L12 13.41l4.89 4.89a1 1 0 0 0 1.41-1.41L13.41 12l4.89-4.89a1 1 0 0 0 0-1.4Z"
451
- ), Gt = F("M11 5h2v6h6v2h-6v6h-2v-6H5v-2h6V5z"), Xt = {
627
+ ), Cn = R("M11 5h2v6h6v2h-6v6h-2v-6H5v-2h6V5z"), On = {
452
628
  key: 0,
453
629
  class: "vpe-toolbar"
454
- }, Yt = ["title", "disabled"], Qt = ["disabled"], en = ["disabled"], tn = ["title", "aria-label"], nn = ["disabled"], rn = {
630
+ }, $n = ["title", "disabled"], Ln = ["disabled"], In = ["disabled"], Mn = ["title", "aria-label"], Rn = ["disabled"], Hn = {
455
631
  class: "vpe-file",
456
632
  title: "当前文件名(下载时使用)"
457
- }, an = ["value", "disabled"], on = ["value"], sn = ["aria-selected", "data-file-id", "title", "onClick", "onKeydown"], ln = { class: "vpe-tab-name" }, un = ["title", "aria-label", "disabled", "onClick"], dn = ["disabled"], cn = { class: "vpe-output-head" }, pn = {
633
+ }, Tn = ["value", "disabled"], Nn = ["value"], jn = ["aria-selected", "data-file-id", "title", "onClick", "onKeydown"], _n = { class: "vpe-tab-name" }, Dn = ["title", "aria-label", "disabled", "onClick"], Un = ["disabled"], Vn = { class: "vpe-output-head" }, Bn = {
458
634
  key: 1,
459
635
  class: "vpe-empty"
460
- }, fn = /* @__PURE__ */ it({
636
+ }, zn = {
637
+ key: 3,
638
+ class: "vpe-fs-panel",
639
+ role: "dialog",
640
+ "aria-label": "虚拟文件"
641
+ }, Kn = { class: "vpe-fs-head" }, An = ["disabled"], qn = { class: "vpe-fs-body" }, Wn = {
642
+ key: 0,
643
+ class: "vpe-fs-empty"
644
+ }, Jn = {
645
+ key: 0,
646
+ class: "vpe-fs-empty"
647
+ }, Zn = ["title"], Gn = { class: "vpe-fs-size" }, Xn = ["title", "aria-label", "onClick"], xe = 1, Yn = /* @__PURE__ */ Nt({
461
648
  __name: "PythonEditor",
462
649
  props: {
463
650
  modelValue: { default: "" },
@@ -476,645 +663,920 @@ const Dt = F(
476
663
  preload: { type: Boolean, default: !1 },
477
664
  pyodideUrl: { default: "" },
478
665
  fileName: { default: "main.py" },
479
- language: { default: "python" }
666
+ language: { default: "python" },
667
+ stdin: { default: "" },
668
+ syncFilesOnRun: { type: Boolean, default: !0 },
669
+ storageKey: { default: "" },
670
+ preloadPackages: { default: () => [] }
480
671
  },
481
- emits: ["update:modelValue", "ready", "statusChange", "runStart", "runOutput", "runError", "runFinish", "loadError", "update:fileName", "update:language", "newFile", "fileClose", "fileSwitch", "copy", "download", "fileOpen"],
482
- setup(s, { expose: n, emit: a }) {
483
- const o = s, i = a, k = O(), w = O(), L = O(), I = O(), x = O([]), H = O("idle"), P = O(!1);
484
- let d = null, me = 0, E = 0, h = null, M = null, Q;
485
- function ee(e, t, r) {
486
- return { id: ++E, name: e, language: t, code: r };
487
- }
488
- const f = O([ee(o.fileName, o.language, o.modelValue)]), z = O(f.value[0].id), c = W(
489
- () => f.value.find((e) => e.id === z.value) ?? f.value[0]
490
- ), j = W({
491
- get: () => c.value.name,
672
+ emits: ["update:modelValue", "ready", "statusChange", "runStart", "runOutput", "runError", "runFinish", "loadError", "update:fileName", "update:language", "newFile", "fileClose", "fileSwitch", "copy", "download", "fileOpen", "fsDownload"],
673
+ setup(u, { expose: r, emit: a }) {
674
+ const i = u, s = a, P = F(), w = F(), I = F(), H = F(), C = F([]), M = F("idle"), T = F(!1), D = F(!1), N = F(!1), j = F([]);
675
+ let J = !1, Z, he = !1, oe = !1, G = !1, o = null, h = 0, x = 0, O = null, U = null, X;
676
+ function le(e, t, n) {
677
+ return { id: ++x, name: e, language: t, code: n };
678
+ }
679
+ const f = F([le(i.fileName, i.language, i.modelValue)]), _ = F(f.value[0].id), y = ie(
680
+ () => f.value.find((e) => e.id === _.value) ?? f.value[0]
681
+ ), A = ie({
682
+ get: () => y.value.name,
492
683
  set: (e) => {
493
- const t = c.value;
494
- t.name !== e && (t.name = e, i("update:fileName", e));
684
+ const t = y.value;
685
+ t.name !== e && (t.name = e, s("update:fileName", e));
495
686
  }
496
- }), ye = new X(), ve = new X(), te = new X(), ne = new X(), N = ze(o.pyodideUrl ? { pyodideUrl: o.pyodideUrl } : void 0), De = W(() => ({
497
- height: typeof o.height == "number" ? `${o.height}px` : o.height
498
- })), _e = W(
499
- () => typeof o.outputHeight == "number" ? `${o.outputHeight}px` : o.outputHeight
500
- ), Be = W(
687
+ }), Pe = new ce(), Ce = new ce(), me = new ce(), ye = new ce(), b = nt(i.pyodideUrl ? { pyodideUrl: i.pyodideUrl } : void 0), rt = ie(() => ({
688
+ height: typeof i.height == "number" ? `${i.height}px` : i.height
689
+ })), at = ie(
690
+ () => typeof i.outputHeight == "number" ? `${i.outputHeight}px` : i.outputHeight
691
+ ), it = ie(
501
692
  () => ({
502
693
  idle: "未加载",
503
694
  loading: "正在加载 Pyodide…",
504
695
  ready: "就绪",
505
696
  running: "运行中"
506
- })[H.value]
697
+ })[M.value]
507
698
  );
508
- function D(e) {
699
+ function Y(e) {
509
700
  return { ...e };
510
701
  }
511
- function re(e, t) {
512
- x.value.push({ id: ++me, stream: e, text: t });
702
+ function Q(e, t) {
703
+ C.value.push({ id: ++h, stream: e, text: t });
704
+ }
705
+ function p(e) {
706
+ Q("system", e);
513
707
  }
514
- function y(e) {
515
- re("system", e);
708
+ function st(e) {
709
+ return fe.some((t) => t.value === e);
710
+ }
711
+ function ot() {
712
+ if (!i.storageKey || typeof window > "u") return null;
713
+ try {
714
+ const e = window.localStorage.getItem(i.storageKey);
715
+ if (!e) return null;
716
+ const t = JSON.parse(e);
717
+ if (t.version !== xe || !Array.isArray(t.files)) return null;
718
+ const n = [];
719
+ for (const m of t.files) {
720
+ if (!m || typeof m.name != "string" || typeof m.code != "string" || !m.name.trim()) continue;
721
+ const k = st(m.language) ? m.language : "python";
722
+ n.push({ name: m.name, language: k, code: m.code });
723
+ }
724
+ if (!n.length) return null;
725
+ const l = typeof t.activeIndex == "number" ? t.activeIndex : 0, d = Math.min(Math.max(Math.trunc(l) || 0, 0), n.length - 1);
726
+ return { version: xe, files: n, activeIndex: d };
727
+ } catch {
728
+ return null;
729
+ }
730
+ }
731
+ function lt() {
732
+ const e = ot();
733
+ if (!e) return;
734
+ f.value = e.files.map((n) => le(n.name, n.language, n.code));
735
+ const t = f.value[e.activeIndex] ?? f.value[0];
736
+ _.value = t.id, p(`已恢复上次编辑内容(${f.value.length} 个文件)`), s("update:modelValue", t.code), s("update:fileName", t.name), s("update:language", t.language);
737
+ }
738
+ function Oe() {
739
+ if (!(!J || oe || !i.storageKey || typeof window > "u"))
740
+ try {
741
+ const e = {
742
+ version: xe,
743
+ files: f.value.map((t) => ({
744
+ name: t.name,
745
+ language: t.language,
746
+ code: t.code
747
+ })),
748
+ activeIndex: Math.max(
749
+ f.value.findIndex((t) => t.id === _.value),
750
+ 0
751
+ )
752
+ };
753
+ window.localStorage.setItem(i.storageKey, JSON.stringify(e));
754
+ } catch (e) {
755
+ he || (he = !0, p(`本地草稿保存失败:${e instanceof Error ? e.message : String(e)}`));
756
+ }
757
+ }
758
+ function ut() {
759
+ !J || !i.storageKey || typeof window > "u" || (oe = !1, window.clearTimeout(Z), Z = window.setTimeout(Oe, 400));
760
+ }
761
+ function dt() {
762
+ if (!(!i.storageKey || typeof window > "u")) {
763
+ window.clearTimeout(Z);
764
+ try {
765
+ window.localStorage.removeItem(i.storageKey), oe = !0, p("已清除本地草稿");
766
+ } catch (e) {
767
+ p(`清除本地草稿失败:${e instanceof Error ? e.message : String(e)}`);
768
+ }
769
+ }
516
770
  }
517
- function _(e) {
518
- if (!d) return;
771
+ function ee(e) {
772
+ if (!o) return;
519
773
  const t = e ? [e] : [];
520
- d.dispatch({ effects: Ue.of(t) });
774
+ o.dispatch({ effects: et.of(t) });
521
775
  }
522
- function Ae() {
523
- const e = o.modelValue;
524
- if (d) {
525
- e !== d.state.doc.toString() && d.dispatch({ changes: { from: 0, to: d.state.doc.length, insert: e } });
776
+ function ct() {
777
+ const e = i.modelValue;
778
+ if (o) {
779
+ e !== o.state.doc.toString() && o.dispatch({ changes: { from: 0, to: o.state.doc.length, insert: e } });
526
780
  return;
527
781
  }
528
- const t = c.value;
782
+ const t = y.value;
529
783
  t.code !== e && (t.code = e);
530
784
  }
531
- function B() {
532
- return d ? d.state.doc.toString() : c.value.code;
785
+ function te() {
786
+ return o ? o.state.doc.toString() : y.value.code;
533
787
  }
534
- function ae(e) {
535
- if (d) {
536
- e !== d.state.doc.toString() && d.dispatch({ changes: { from: 0, to: d.state.doc.length, insert: e } });
788
+ function ge(e) {
789
+ if (o) {
790
+ e !== o.state.doc.toString() && o.dispatch({ changes: { from: 0, to: o.state.doc.length, insert: e } });
537
791
  return;
538
792
  }
539
- const t = c.value;
540
- t.code = e, e !== o.modelValue && i("update:modelValue", e);
793
+ const t = y.value;
794
+ t.code = e, e !== i.modelValue && s("update:modelValue", e);
541
795
  }
542
- function oe(e) {
543
- return o.disableLint || e !== "python" ? [] : jt(N, o.lintDelay);
796
+ function ve(e) {
797
+ return i.disableLint || e !== "python" ? [] : yn(b, i.lintDelay);
544
798
  }
545
- function ge(e) {
546
- const t = c.value;
799
+ function $e(e) {
800
+ const t = y.value;
547
801
  if (t.language !== e) {
548
- if (t.language = e, _(void 0), d == null || d.dispatch({
802
+ if (t.language = e, ee(void 0), o == null || o.dispatch({
549
803
  effects: [
550
- te.reconfigure(de(e)),
551
- ne.reconfigure(oe(e))
804
+ me.reconfigure(we(e)),
805
+ ye.reconfigure(ve(e))
552
806
  ]
553
807
  }), /^untitled(-\d+)?\.[^.]+$/.test(t.name)) {
554
- const l = `${t.name.slice(0, t.name.lastIndexOf("."))}.${Y(e).extension}`;
555
- f.value.some((u) => u.id !== t.id && u.name === l) || (t.name = l, i("update:fileName", l));
808
+ const l = `${t.name.slice(0, t.name.lastIndexOf("."))}.${pe(e).extension}`;
809
+ f.value.some((d) => d.id !== t.id && d.name === l) || (t.name = l, s("update:fileName", l));
556
810
  }
557
- i("update:language", e);
811
+ s("update:language", e);
558
812
  }
559
813
  }
560
- function ke(e, t) {
814
+ function Le(e, t) {
561
815
  const l = e.trim().replace(/[\\/:*?"<>|]+/g, "_").replace(/\.+$/, "") || "untitled";
562
- return /\.[^.\\/]+$/.test(l) ? l : `${l}.${Y(t).extension}`;
816
+ return /\.[^.\\/]+$/.test(l) ? l : `${l}.${pe(t).extension}`;
563
817
  }
564
- function qe(e) {
565
- const t = Y(e).extension, r = new Set(f.value.map((g) => g.name));
566
- let l = `untitled.${t}`, u = 2;
567
- for (; r.has(l); )
568
- l = `untitled-${u}.${t}`, u += 1;
818
+ function pt(e) {
819
+ const t = pe(e).extension, n = new Set(f.value.map((m) => m.name));
820
+ let l = `untitled.${t}`, d = 2;
821
+ for (; n.has(l); )
822
+ l = `untitled-${d}.${t}`, d += 1;
569
823
  return l;
570
824
  }
571
- function Ke(e) {
572
- if (!f.value.some((m) => m.name === e)) return e;
573
- const t = e.lastIndexOf("."), r = t > 0 ? e.slice(0, t) : e, l = t > 0 ? e.slice(t) : "";
574
- let u = 2, g = `${r}-${u}${l}`;
575
- for (; f.value.some((m) => m.name === g); )
576
- u += 1, g = `${r}-${u}${l}`;
577
- return g;
578
- }
579
- let A = 0;
580
- async function be() {
581
- var u, g;
582
- if (H.value === "loading" || H.value === "running") return;
583
- const e = c.value.language;
825
+ function ft(e) {
826
+ if (!f.value.some((k) => k.name === e)) return e;
827
+ const t = e.lastIndexOf("."), n = t > 0 ? e.slice(0, t) : e, l = t > 0 ? e.slice(t) : "";
828
+ let d = 2, m = `${n}-${d}${l}`;
829
+ for (; f.value.some((k) => k.name === m); )
830
+ d += 1, m = `${n}-${d}${l}`;
831
+ return m;
832
+ }
833
+ let ne = 0;
834
+ function ht(e) {
835
+ return !!e && e !== "." && e !== ".." && !e.includes("/") && !e.includes("\\");
836
+ }
837
+ async function mt() {
838
+ var t;
839
+ if (!i.syncFilesOnRun) return;
840
+ const e = f.value.filter((n) => n.language === "python");
841
+ for (const n of e) {
842
+ if (!ht(n.name)) {
843
+ p(`跳过同步文件:${n.name}(文件名不能包含路径分隔符)`);
844
+ continue;
845
+ }
846
+ const l = await b.writeFile(n.name, n.code);
847
+ l.ok || p(`同步文件失败:${n.name}(${((t = l.error) == null ? void 0 : t.message) ?? "未知错误"})`);
848
+ }
849
+ }
850
+ async function Ie() {
851
+ var d, m, k;
852
+ if (M.value === "loading" || M.value === "running") return;
853
+ const e = y.value.language;
584
854
  if (e !== "python") {
585
- y(`当前文件为 ${Y(e).label},仅支持执行 Python 代码`);
855
+ p(`当前文件为 ${pe(e).label},仅支持执行 Python 代码`);
586
856
  return;
587
857
  }
588
- A += 1;
589
- const t = A, r = c.value.id;
590
- _(void 0), o.clearOutputOnRun && (x.value = []), y("开始执行"), i("runStart");
591
- const l = B();
858
+ ne += 1;
859
+ const t = ne, n = y.value.id;
860
+ ee(void 0), i.clearOutputOnRun && (C.value = []), p("开始执行"), s("runStart");
861
+ const l = te();
592
862
  try {
593
- const m = await N.run(l, {
594
- onOutput: (q, K) => {
595
- re(q, K), i("runOutput", { stream: q, text: K });
863
+ await mt();
864
+ const E = await b.run(l, {
865
+ stdin: i.stdin,
866
+ onOutput: (re, ae) => {
867
+ Q(re, ae), s("runOutput", { stream: re, text: ae });
596
868
  }
597
869
  });
598
- if (t !== A) return;
599
- m.interrupted ? y("执行已中断") : m.ok ? y(`执行完成,耗时 ${(m.durationMs / 1e3).toFixed(2)}s`) : (y(`执行出错:${((u = m.error) == null ? void 0 : u.type) ?? "未知错误"}`), c.value.id === r && _((g = m.error) == null ? void 0 : g.line), m.error && i("runError", m.error)), i("runFinish", m);
600
- } catch (m) {
601
- if (t !== A) return;
602
- const q = m instanceof Error ? m.message : String(m);
603
- y(`执行失败:${q}`);
604
- const K = { type: "RuntimeError", message: q, traceback: "" };
605
- i("runError", K), i("runFinish", { ok: !1, durationMs: 0, error: K });
870
+ if (t !== ne) return;
871
+ E.interrupted ? p("执行已中断") : E.ok ? p(`执行完成,耗时 ${(E.durationMs / 1e3).toFixed(2)}s`) : (p(`执行出错:${((d = E.error) == null ? void 0 : d.type) ?? "未知错误"}`), (m = E.error) != null && m.traceback && (Q("stderr", E.error.traceback), s("runOutput", { stream: "stderr", text: E.error.traceback })), y.value.id === n && ee((k = E.error) == null ? void 0 : k.line), E.error && s("runError", E.error)), s("runFinish", E);
872
+ } catch (E) {
873
+ if (t !== ne) return;
874
+ const re = E instanceof Error ? E.message : String(E);
875
+ p(`执行失败:${re}`);
876
+ const ae = { type: "RuntimeError", message: re, traceback: "" };
877
+ s("runError", ae), s("runFinish", { ok: !1, durationMs: 0, error: ae });
606
878
  }
607
879
  }
608
- st(() => {
609
- const e = k.value;
880
+ async function yt() {
881
+ var t;
882
+ if (G) return;
883
+ const e = i.preloadPackages;
884
+ if (e.length) {
885
+ G = !0, p(`正在安装预置包:${e.join(", ")}`);
886
+ try {
887
+ const n = await b.loadPackages(e, {
888
+ onOutput: (l, d) => Q(l, d)
889
+ });
890
+ p(
891
+ n.ok ? `预置包安装完成(${(n.durationMs / 1e3).toFixed(1)}s)` : `预置包安装失败:${((t = n.error) == null ? void 0 : t.message) ?? "未知错误"}`
892
+ );
893
+ } catch (n) {
894
+ p(`预置包安装失败:${n instanceof Error ? n.message : String(n)}`);
895
+ }
896
+ }
897
+ }
898
+ jt(() => {
899
+ const e = P.value;
610
900
  if (!e) return;
901
+ lt(), J = !0;
611
902
  const t = [
612
- ye.of(o.theme === "dark" ? [fe] : []),
613
- ve.of([
614
- ce.readOnly.of(o.readOnly),
615
- R.editable.of(!o.readOnly)
903
+ Pe.of(i.theme === "dark" ? [Fe] : []),
904
+ Ce.of([
905
+ Se.readOnly.of(i.readOnly),
906
+ K.editable.of(!i.readOnly)
616
907
  ]),
617
- ne.of(oe(c.value.language))
908
+ ye.of(ve(y.value.language))
618
909
  ];
619
910
  try {
620
- d = Rt(e, {
621
- value: c.value.code,
622
- dark: o.theme === "dark",
623
- placeholderText: o.placeholder,
624
- language: te.of(de(c.value.language)),
911
+ o = mn(e, {
912
+ value: y.value.code,
913
+ dark: i.theme === "dark",
914
+ placeholderText: i.placeholder,
915
+ language: me.of(we(y.value.language)),
625
916
  extensions: t,
626
- onDocChange: (r) => {
627
- c.value.code = r, r !== o.modelValue && i("update:modelValue", r);
917
+ onDocChange: (n) => {
918
+ y.value.code = n, n !== i.modelValue && s("update:modelValue", n);
628
919
  },
629
- onRunShortcut: be
920
+ onRunShortcut: Ie
630
921
  });
631
- } catch (r) {
632
- const l = r instanceof Error ? r.message : String(r);
633
- console.error("[princess-python-editor] 编辑器初始化失败", r), y(`编辑器初始化失败:${l}`), e.innerHTML = "";
634
- const u = document.createElement("div");
635
- u.className = "vpe-init-error", u.textContent = `编辑器初始化失败:${l}`, e.appendChild(u);
922
+ } catch (n) {
923
+ const l = n instanceof Error ? n.message : String(n);
924
+ console.error("[princess-python-editor] 编辑器初始化失败", n), p(`编辑器初始化失败:${l}`), e.innerHTML = "";
925
+ const d = document.createElement("div");
926
+ d.className = "vpe-init-error", d.textContent = `编辑器初始化失败:${l}`, e.appendChild(d);
636
927
  return;
637
928
  }
638
- o.autofocus && d.focus(), h = N.on("status", (r, l) => {
639
- H.value = r, r === "ready" && (l && y(`Pyodide ${l} 就绪`), i("ready"), d && !o.disableLint && c.value.language === "python" && wt(d)), i("statusChange", r);
640
- }), M = N.on("initError", (r) => {
641
- y(`Pyodide 加载失败:${r}`), i("loadError", r);
642
- }), H.value = N.status, o.preload && N.waitReady().catch((r) => y(r.message));
643
- }), lt(() => {
644
- h == null || h(), M == null || M(), window.clearTimeout(Q), d == null || d.destroy(), d = null;
645
- }), U(
646
- () => o.modelValue,
647
- () => Ae()
648
- ), U(
649
- () => o.fileName,
929
+ i.autofocus && o.focus(), O = b.on("status", (n, l) => {
930
+ M.value = n, n === "ready" && (l && p(`Pyodide ${l} 就绪`), s("ready"), o && !i.disableLint && y.value.language === "python" && Xt(o)), s("statusChange", n);
931
+ }), U = b.on("initError", (n) => {
932
+ p(`Pyodide 加载失败:${n}`), s("loadError", n);
933
+ }), M.value = b.status, i.preloadPackages.length ? b.waitReady().then(() => yt()).catch((n) => p(n.message)) : i.preload && b.waitReady().catch((n) => p(n.message));
934
+ }), _t(() => {
935
+ O == null || O(), U == null || U(), window.clearTimeout(X), window.clearTimeout(Z), Oe(), o == null || o.destroy(), o = null;
936
+ }), V(
937
+ () => i.modelValue,
938
+ () => ct()
939
+ ), V(
940
+ () => i.fileName,
650
941
  (e) => {
651
- e && e !== c.value.name && (j.value = e);
942
+ e && e !== y.value.name && (A.value = e);
652
943
  }
653
- ), U(
654
- () => o.language,
944
+ ), V(
945
+ () => i.language,
655
946
  (e) => {
656
- e !== c.value.language && ge(e);
947
+ e !== y.value.language && $e(e);
657
948
  }
658
- ), U(
659
- () => o.theme,
949
+ ), V(
950
+ () => i.theme,
660
951
  (e) => {
661
- d == null || d.dispatch({ effects: ye.reconfigure(e === "dark" ? [fe] : []) });
952
+ o == null || o.dispatch({ effects: Pe.reconfigure(e === "dark" ? [Fe] : []) });
662
953
  }
663
- ), U(
664
- () => o.readOnly,
954
+ ), V(
955
+ () => i.readOnly,
665
956
  (e) => {
666
- d == null || d.dispatch({
667
- effects: ve.reconfigure([ce.readOnly.of(e), R.editable.of(!e)])
957
+ o == null || o.dispatch({
958
+ effects: Ce.reconfigure([Se.readOnly.of(e), K.editable.of(!e)])
668
959
  });
669
960
  }
670
- ), U(
671
- () => x.value.length,
961
+ ), V(
962
+ () => C.value.length,
672
963
  async () => {
673
- await Ie();
964
+ await Ae();
674
965
  const e = w.value;
675
966
  e && (e.scrollTop = e.scrollHeight);
676
967
  }
677
- );
678
- function we() {
679
- be();
968
+ ), V([f, _], () => ut(), { deep: !0 });
969
+ function Me() {
970
+ Ie();
680
971
  }
681
- function xe() {
682
- H.value === "running" && (A += 1, N.interrupt(), y("执行已中断"));
972
+ function Re() {
973
+ M.value === "running" && (ne += 1, b.interrupt(), p("执行已中断"));
683
974
  }
684
- function Ee() {
685
- x.value = [];
975
+ function He() {
976
+ C.value = [];
686
977
  }
687
- function ie() {
688
- if (o.readOnly) return;
689
- const e = c.value.language, t = ee(qe(e), e, "");
690
- f.value.push(t), T(t.id), i("newFile", D(t));
978
+ function ke() {
979
+ if (i.readOnly) return;
980
+ const e = y.value.language, t = le(pt(e), e, "");
981
+ f.value.push(t), q(t.id), s("newFile", Y(t));
691
982
  }
692
- function T(e) {
693
- if (e === z.value) {
694
- Z();
983
+ function q(e) {
984
+ if (e === _.value) {
985
+ ue();
695
986
  return;
696
987
  }
697
- const t = f.value.find((r) => r.id === e);
698
- t && (z.value = e, Ce(t));
988
+ const t = f.value.find((n) => n.id === e);
989
+ t && (_.value = e, Ne(t));
699
990
  }
700
- function Se(e) {
991
+ function Te(e) {
701
992
  if (f.value.length <= 1) return;
702
- const t = f.value.findIndex((u) => u.id === e);
993
+ const t = f.value.findIndex((d) => d.id === e);
703
994
  if (t === -1) return;
704
- const r = f.value.splice(t, 1)[0];
705
- if (!r || (i("fileClose", D(r)), e !== z.value)) return;
995
+ const n = f.value.splice(t, 1)[0];
996
+ if (!n || (s("fileClose", Y(n)), e !== _.value)) return;
706
997
  const l = f.value[Math.min(t, f.value.length - 1)];
707
- l && (z.value = l.id, Ce(l));
998
+ l && (_.value = l.id, Ne(l));
708
999
  }
709
- function Ce(e) {
710
- _(void 0), ae(e.code), d == null || d.dispatch({
1000
+ function Ne(e) {
1001
+ ee(void 0), ge(e.code), o == null || o.dispatch({
711
1002
  effects: [
712
- te.reconfigure(de(e.language)),
713
- ne.reconfigure(oe(e.language))
1003
+ me.reconfigure(we(e.language)),
1004
+ ye.reconfigure(ve(e.language))
714
1005
  ]
715
- }), i("update:fileName", e.name), i("update:language", e.language), i("fileSwitch", D(e)), Z();
1006
+ }), s("update:fileName", e.name), s("update:language", e.language), s("fileSwitch", Y(e)), ue();
716
1007
  }
717
- function Oe() {
718
- o.readOnly || (_(void 0), ae(""), Z());
1008
+ function je() {
1009
+ i.readOnly || (ee(void 0), ge(""), ue());
719
1010
  }
720
- async function Le() {
721
- var r;
722
- const e = B();
1011
+ async function _e() {
1012
+ var n;
1013
+ const e = te();
723
1014
  let t = !1;
724
1015
  try {
725
- (r = navigator.clipboard) != null && r.writeText && (await navigator.clipboard.writeText(e), t = !0);
1016
+ (n = navigator.clipboard) != null && n.writeText && (await navigator.clipboard.writeText(e), t = !0);
726
1017
  } catch {
727
1018
  t = !1;
728
1019
  }
729
- return t || (t = We(e)), t ? (P.value = !0, window.clearTimeout(Q), Q = window.setTimeout(() => {
730
- P.value = !1;
731
- }, 1600), i("copy", e), !0) : (y("复制失败,请手动选择代码复制"), !1);
1020
+ return t || (t = gt(e)), t ? (T.value = !0, window.clearTimeout(X), X = window.setTimeout(() => {
1021
+ T.value = !1;
1022
+ }, 1600), s("copy", e), !0) : (p("复制失败,请手动选择代码复制"), !1);
732
1023
  }
733
- function We(e) {
1024
+ function gt(e) {
734
1025
  const t = document.createElement("textarea");
735
1026
  t.value = e, t.setAttribute("readonly", ""), t.style.position = "fixed", t.style.top = "0", t.style.left = "-9999px", t.style.opacity = "0", document.body.appendChild(t), t.select(), t.setSelectionRange(0, t.value.length);
736
- let r = !1;
1027
+ let n = !1;
737
1028
  try {
738
- r = document.execCommand("copy");
1029
+ n = document.execCommand("copy");
739
1030
  } catch {
740
- r = !1;
1031
+ n = !1;
741
1032
  }
742
- return t.remove(), r;
1033
+ return t.remove(), n;
743
1034
  }
744
- function Fe() {
745
- const e = c.value, t = ke(e.name, e.language);
746
- j.value = t;
747
- const r = new Blob([B()], {
1035
+ function De() {
1036
+ const e = y.value, t = Le(e.name, e.language);
1037
+ A.value = t;
1038
+ const n = new Blob([te()], {
748
1039
  type: e.language === "python" ? "text/x-python;charset=utf-8" : "text/plain;charset=utf-8"
749
- }), l = URL.createObjectURL(r), u = document.createElement("a");
750
- return u.href = l, u.download = t, u.style.display = "none", document.body.appendChild(u), u.click(), u.remove(), window.setTimeout(() => URL.revokeObjectURL(l), 1e3), i("download", t), t;
1040
+ }), l = URL.createObjectURL(n), d = document.createElement("a");
1041
+ return d.href = l, d.download = t, d.style.display = "none", document.body.appendChild(d), d.click(), d.remove(), window.setTimeout(() => URL.revokeObjectURL(l), 1e3), s("download", t), t;
751
1042
  }
752
- function He() {
1043
+ function vt() {
1044
+ D.value = !D.value, D.value && Ue();
1045
+ }
1046
+ async function Ue() {
1047
+ var e;
1048
+ if (!N.value) {
1049
+ N.value = !0;
1050
+ try {
1051
+ const t = await b.listFiles(".");
1052
+ if (!t.ok) {
1053
+ j.value = [], p(`读取虚拟文件失败:${((e = t.error) == null ? void 0 : e.message) ?? "未知错误"}`);
1054
+ return;
1055
+ }
1056
+ j.value = t.entries ?? [];
1057
+ } catch (t) {
1058
+ j.value = [], p(`读取虚拟文件失败:${t instanceof Error ? t.message : String(t)}`);
1059
+ } finally {
1060
+ N.value = !1;
1061
+ }
1062
+ }
1063
+ }
1064
+ function kt(e) {
1065
+ switch (e.slice(e.lastIndexOf(".") + 1).toLowerCase()) {
1066
+ case "csv":
1067
+ return "text/csv";
1068
+ case "json":
1069
+ return "application/json";
1070
+ case "html":
1071
+ case "htm":
1072
+ return "text/html";
1073
+ case "md":
1074
+ return "text/markdown";
1075
+ case "py":
1076
+ return "text/x-python";
1077
+ default:
1078
+ return "text/plain";
1079
+ }
1080
+ }
1081
+ function bt(e) {
1082
+ return e < 1024 ? `${e} B` : e < 1024 * 1024 ? `${(e / 1024).toFixed(1)} KB` : `${(e / 1024 / 1024).toFixed(1)} MB`;
1083
+ }
1084
+ async function Ve(e) {
1085
+ var t;
1086
+ try {
1087
+ const n = await b.readFile(e);
1088
+ if (!n.ok || n.content === void 0)
1089
+ return p(`下载失败:${e}(${((t = n.error) == null ? void 0 : t.message) ?? "未知错误"})`), null;
1090
+ const l = e.slice(e.lastIndexOf("/") + 1) || "download.txt", d = new Blob([n.content], {
1091
+ type: `${kt(l)};charset=utf-8`
1092
+ }), m = URL.createObjectURL(d), k = document.createElement("a");
1093
+ return k.href = m, k.download = l, k.style.display = "none", document.body.appendChild(k), k.click(), k.remove(), window.setTimeout(() => URL.revokeObjectURL(m), 1e3), s("fsDownload", { path: n.path ?? e, name: l }), p(`已下载虚拟文件:${l}`), l;
1094
+ } catch (n) {
1095
+ return p(`下载失败:${n instanceof Error ? n.message : String(n)}`), null;
1096
+ }
1097
+ }
1098
+ function wt(e, t) {
1099
+ return b.writeFile(e, t);
1100
+ }
1101
+ function xt(e) {
1102
+ return b.readFile(e);
1103
+ }
1104
+ function St(e = ".") {
1105
+ return b.listFiles(e);
1106
+ }
1107
+ function Be() {
753
1108
  var e;
754
- (e = I.value) == null || e.click();
1109
+ (e = H.value) == null || e.click();
755
1110
  }
756
- async function Ze(e) {
1111
+ async function Et(e) {
757
1112
  var l;
758
- const t = e.target, r = (l = t.files) == null ? void 0 : l[0];
759
- if (t.value = "", !!r) {
760
- if (r.size > 2 * 1024 * 1024) {
761
- y(`文件过大:${(r.size / 1024 / 1024).toFixed(1)} MB(最多 2 MB)`);
1113
+ const t = e.target, n = (l = t.files) == null ? void 0 : l[0];
1114
+ if (t.value = "", !!n) {
1115
+ if (n.size > 2 * 1024 * 1024) {
1116
+ p(`文件过大:${(n.size / 1024 / 1024).toFixed(1)} MB(最多 2 MB)`);
762
1117
  return;
763
1118
  }
764
1119
  try {
765
- const u = await r.text(), g = zt(r.name), m = ee(Ke(r.name), g, u);
766
- f.value.push(m), T(m.id), y(`已打开文件:${m.name}`), i("fileOpen", { name: m.name, code: u, language: g });
767
- } catch (u) {
768
- const g = u instanceof Error ? u.message : String(u);
769
- y(`读取文件失败:${g}`);
1120
+ const d = await n.text(), m = bn(n.name), k = le(ft(n.name), m, d);
1121
+ f.value.push(k), q(k.id), p(`已打开文件:${k.name}`), s("fileOpen", { name: k.name, code: d, language: m });
1122
+ } catch (d) {
1123
+ const m = d instanceof Error ? d.message : String(d);
1124
+ p(`读取文件失败:${m}`);
770
1125
  }
771
1126
  }
772
1127
  }
773
- function Je() {
774
- j.value = ke(j.value, c.value.language);
1128
+ function Ft() {
1129
+ A.value = Le(A.value, y.value.language);
775
1130
  }
776
- function Ge(e) {
1131
+ function Pt(e) {
777
1132
  e.key === "Enter" && (e.preventDefault(), e.target.blur());
778
1133
  }
779
- function Xe(e) {
780
- ge(e.target.value);
1134
+ function Ct(e) {
1135
+ $e(e.target.value);
781
1136
  }
782
- async function Me(e) {
783
- var t, r;
784
- await Ie(), (r = (t = L.value) == null ? void 0 : t.querySelector(`[data-file-id="${e}"]`)) == null || r.focus();
1137
+ async function ze(e) {
1138
+ var t, n;
1139
+ await Ae(), (n = (t = I.value) == null ? void 0 : t.querySelector(`[data-file-id="${e}"]`)) == null || n.focus();
785
1140
  }
786
- function Ye(e, t) {
1141
+ function Ot(e, t) {
787
1142
  if (e.target !== e.currentTarget) return;
788
1143
  if (e.key === "Enter" || e.key === " ") {
789
- e.preventDefault(), T(t.id), Me(t.id);
1144
+ e.preventDefault(), q(t.id), ze(t.id);
790
1145
  return;
791
1146
  }
792
1147
  if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
793
1148
  e.preventDefault();
794
- const r = f.value.findIndex((g) => g.id === t.id);
795
- if (r < 0) return;
796
- const l = e.key === "ArrowLeft" ? -1 : 1, u = f.value[(r + l + f.value.length) % f.value.length];
797
- u && (T(u.id), Me(u.id));
1149
+ const n = f.value.findIndex((m) => m.id === t.id);
1150
+ if (n < 0) return;
1151
+ const l = e.key === "ArrowLeft" ? -1 : 1, d = f.value[(n + l + f.value.length) % f.value.length];
1152
+ d && (q(d.id), ze(d.id));
798
1153
  }
799
- function Z() {
800
- d == null || d.focus();
1154
+ function ue() {
1155
+ o == null || o.focus();
801
1156
  }
802
- async function Qe(e) {
803
- var r;
804
- y(`正在安装:${e.join(", ")}`);
1157
+ async function $t(e) {
1158
+ var n;
1159
+ p(`正在安装:${e.join(", ")}`);
805
1160
  let t;
806
1161
  try {
807
- t = await N.loadPackages(e, {
808
- onOutput: (l, u) => re(l, u)
1162
+ t = await b.loadPackages(e, {
1163
+ onOutput: (l, d) => Q(l, d)
809
1164
  });
810
1165
  } catch (l) {
811
- const u = l instanceof Error ? l.message : String(l);
812
- return y(`安装失败:${u}`), { ok: !1, durationMs: 0, error: { type: "RuntimeError", message: u } };
1166
+ const d = l instanceof Error ? l.message : String(l);
1167
+ return p(`安装失败:${d}`), { ok: !1, durationMs: 0, error: { type: "RuntimeError", message: d } };
813
1168
  }
814
- return y(t.ok ? "安装完成" : `安装失败:${((r = t.error) == null ? void 0 : r.message) ?? "未知错误"}`), t;
815
- }
816
- function et() {
817
- return N.checkSyntax(B());
818
- }
819
- function tt() {
820
- return d;
821
- }
822
- function nt() {
823
- return f.value.map(D);
824
- }
825
- function rt() {
826
- return D(c.value);
827
- }
828
- return n({
829
- run: we,
830
- stop: xe,
831
- clearOutput: Ee,
832
- clearCode: Oe,
833
- newFile: ie,
834
- switchFile: T,
835
- closeFile: Se,
836
- copyCode: Le,
837
- download: Fe,
838
- openFile: He,
839
- focus: Z,
840
- install: Qe,
841
- checkSyntax: et,
842
- getEditorView: tt,
843
- getCode: B,
844
- setCode: ae,
845
- getFiles: nt,
846
- getActiveFile: rt
847
- }), (e, t) => (v(), b("div", {
848
- class: V(["vpe-root", { "vpe-dark": s.theme === "dark" }]),
849
- style: Ne(De.value)
1169
+ return p(t.ok ? "安装完成" : `安装失败:${((n = t.error) == null ? void 0 : n.message) ?? "未知错误"}`), t;
1170
+ }
1171
+ function Lt() {
1172
+ return b.checkSyntax(te());
1173
+ }
1174
+ function It() {
1175
+ return o;
1176
+ }
1177
+ function Mt() {
1178
+ return f.value.map(Y);
1179
+ }
1180
+ function Rt() {
1181
+ return Y(y.value);
1182
+ }
1183
+ return r({
1184
+ run: Me,
1185
+ stop: Re,
1186
+ clearOutput: He,
1187
+ clearCode: je,
1188
+ newFile: ke,
1189
+ switchFile: q,
1190
+ closeFile: Te,
1191
+ copyCode: _e,
1192
+ download: De,
1193
+ openFile: Be,
1194
+ focus: ue,
1195
+ install: $t,
1196
+ checkSyntax: Lt,
1197
+ getEditorView: It,
1198
+ getCode: te,
1199
+ setCode: ge,
1200
+ getFiles: Mt,
1201
+ getActiveFile: Rt,
1202
+ writeFile: wt,
1203
+ readFile: xt,
1204
+ listFiles: St,
1205
+ downloadFile: Ve,
1206
+ clearPersistedState: dt
1207
+ }), (e, t) => (g(), v("div", {
1208
+ class: B(["vpe-root", { "vpe-dark": u.theme === "dark" }]),
1209
+ style: qe(rt.value)
850
1210
  }, [
851
- s.showToolbar ? (v(), b("div", Xt, [
852
- H.value !== "running" ? (v(), b("button", {
1211
+ u.showToolbar ? (g(), v("div", On, [
1212
+ M.value !== "running" ? (g(), v("button", {
853
1213
  key: 0,
854
1214
  class: "vpe-btn vpe-btn--primary",
855
1215
  type: "button",
856
- title: c.value.language === "python" ? "运行 (Ctrl+Enter)" : "仅支持执行 Python 文件",
857
- disabled: H.value === "loading" || c.value.language !== "python",
858
- onClick: we
1216
+ title: y.value.language === "python" ? "运行 (Ctrl+Enter)" : "仅支持执行 Python 文件",
1217
+ disabled: M.value === "loading" || y.value.language !== "python",
1218
+ onClick: Me
859
1219
  }, [
860
- $(S(Dt)),
861
- t[1] || (t[1] = p("span", null, "运行", -1))
862
- ], 8, Yt)) : (v(), b("button", {
1220
+ $(S(wn)),
1221
+ t[2] || (t[2] = c("span", null, "运行", -1))
1222
+ ], 8, $n)) : (g(), v("button", {
863
1223
  key: 1,
864
1224
  class: "vpe-btn vpe-btn--stop",
865
1225
  type: "button",
866
1226
  title: "中断执行",
867
- onClick: xe
1227
+ onClick: Re
868
1228
  }, [
869
- $(S(_t)),
870
- t[2] || (t[2] = p("span", null, "停止", -1))
1229
+ $(S(xn)),
1230
+ t[3] || (t[3] = c("span", null, "停止", -1))
871
1231
  ])),
872
- t[4] || (t[4] = p("span", {
1232
+ t[6] || (t[6] = c("span", {
873
1233
  class: "vpe-divider",
874
1234
  "aria-hidden": "true"
875
1235
  }, null, -1)),
876
- p("button", {
1236
+ c("button", {
877
1237
  class: "vpe-btn",
878
1238
  type: "button",
879
1239
  title: "新建文件",
880
1240
  "aria-label": "新建文件",
881
- disabled: s.readOnly,
882
- onClick: ie
1241
+ disabled: u.readOnly,
1242
+ onClick: ke
883
1243
  }, [
884
- $(S(Bt))
885
- ], 8, Qt),
886
- p("button", {
1244
+ $(S(Sn))
1245
+ ], 8, Ln),
1246
+ c("button", {
887
1247
  class: "vpe-btn",
888
1248
  type: "button",
889
1249
  title: "打开本地文件",
890
1250
  "aria-label": "打开本地文件",
891
- disabled: s.readOnly,
892
- onClick: He
1251
+ disabled: u.readOnly,
1252
+ onClick: Be
893
1253
  }, [
894
- $(S(At))
895
- ], 8, en),
896
- p("button", {
1254
+ $(S(En))
1255
+ ], 8, In),
1256
+ c("button", {
897
1257
  class: "vpe-btn",
898
1258
  type: "button",
899
1259
  title: "下载当前文件",
900
1260
  "aria-label": "下载当前文件",
901
- onClick: Fe
1261
+ onClick: De
902
1262
  }, [
903
- $(S(Kt))
1263
+ $(S(Xe))
904
1264
  ]),
905
- p("button", {
906
- class: V(["vpe-btn", { "vpe-btn--copied": P.value }]),
1265
+ c("button", {
1266
+ class: "vpe-btn",
907
1267
  type: "button",
908
- title: P.value ? "已复制" : "复制代码",
909
- "aria-label": P.value ? "已复制" : "复制代码",
910
- onClick: Le
1268
+ title: "虚拟文件(下载 Python 生成的文件)",
1269
+ "aria-label": "虚拟文件",
1270
+ onClick: vt
911
1271
  }, [
912
- P.value ? (v(), Pe(S(Zt), { key: 0 })) : (v(), Pe(S(Wt), { key: 1 }))
913
- ], 10, tn),
914
- p("button", {
1272
+ $(S(Ge)),
1273
+ t[4] || (t[4] = c("span", null, "虚拟文件", -1))
1274
+ ]),
1275
+ c("button", {
1276
+ class: B(["vpe-btn", { "vpe-btn--copied": T.value }]),
1277
+ type: "button",
1278
+ title: T.value ? "已复制" : "复制代码",
1279
+ "aria-label": T.value ? "已复制" : "复制代码",
1280
+ onClick: _e
1281
+ }, [
1282
+ T.value ? (g(), We(S(Pn), { key: 0 })) : (g(), We(S(Fn), { key: 1 }))
1283
+ ], 10, Mn),
1284
+ c("button", {
915
1285
  class: "vpe-btn",
916
1286
  type: "button",
917
1287
  title: "清空当前文件",
918
1288
  "aria-label": "清空当前文件",
919
- disabled: s.readOnly,
920
- onClick: Oe
1289
+ disabled: u.readOnly,
1290
+ onClick: je
921
1291
  }, [
922
- $(S(je))
923
- ], 8, nn),
924
- t[5] || (t[5] = p("span", {
1292
+ $(S(Ze))
1293
+ ], 8, Rn),
1294
+ t[7] || (t[7] = c("span", {
925
1295
  class: "vpe-divider",
926
1296
  "aria-hidden": "true"
927
1297
  }, null, -1)),
928
- p("label", rn, [
929
- $(S(qt)),
930
- ut(p("input", {
931
- "onUpdate:modelValue": t[0] || (t[0] = (r) => j.value = r),
1298
+ c("label", Hn, [
1299
+ $(S(Ge)),
1300
+ Dt(c("input", {
1301
+ "onUpdate:modelValue": t[0] || (t[0] = (n) => A.value = n),
932
1302
  class: "vpe-file-input",
933
1303
  type: "text",
934
1304
  spellcheck: "false",
935
1305
  "aria-label": "文件名",
936
- onBlur: Je,
937
- onKeydown: Ge
1306
+ onBlur: Ft,
1307
+ onKeydown: Pt
938
1308
  }, null, 544), [
939
- [dt, j.value]
1309
+ [Ut, A.value]
940
1310
  ])
941
1311
  ]),
942
- t[6] || (t[6] = p("span", {
1312
+ t[8] || (t[8] = c("span", {
943
1313
  class: "vpe-spacer",
944
1314
  "aria-hidden": "true"
945
1315
  }, null, -1)),
946
- p("span", {
947
- class: V(["vpe-status", `vpe-status--${H.value}`])
1316
+ c("span", {
1317
+ class: B(["vpe-status", `vpe-status--${M.value}`])
948
1318
  }, [
949
- t[3] || (t[3] = p("span", {
1319
+ t[5] || (t[5] = c("span", {
950
1320
  class: "vpe-status-dot",
951
1321
  "aria-hidden": "true"
952
1322
  }, null, -1)),
953
- p("span", null, J(Be.value), 1)
1323
+ c("span", null, W(it.value), 1)
954
1324
  ], 2),
955
- p("select", {
1325
+ c("select", {
956
1326
  class: "vpe-lang",
957
- value: c.value.language,
1327
+ value: y.value.language,
958
1328
  title: "编辑器语言",
959
1329
  "aria-label": "编辑器语言",
960
- disabled: s.readOnly,
961
- onChange: Xe
1330
+ disabled: u.readOnly,
1331
+ onChange: Ct
962
1332
  }, [
963
- (v(!0), b(se, null, le(S(he), (r) => (v(), b("option", {
964
- key: r.value,
965
- value: r.value
966
- }, J(r.label), 9, on))), 128))
967
- ], 40, an)
968
- ])) : G("", !0),
969
- s.showTabs ? (v(), b("div", {
1333
+ (g(!0), v(se, null, de(S(fe), (n) => (g(), v("option", {
1334
+ key: n.value,
1335
+ value: n.value
1336
+ }, W(n.label), 9, Nn))), 128))
1337
+ ], 40, Tn)
1338
+ ])) : z("", !0),
1339
+ u.showTabs ? (g(), v("div", {
970
1340
  key: 1,
971
1341
  ref_key: "tabsEl",
972
- ref: L,
1342
+ ref: I,
973
1343
  class: "vpe-tabs",
974
1344
  role: "tablist",
975
1345
  "aria-label": "文件"
976
1346
  }, [
977
- (v(!0), b(se, null, le(f.value, (r) => (v(), b("div", {
978
- key: r.id,
979
- class: V(["vpe-tab", { "vpe-tab--active": r.id === c.value.id }]),
1347
+ (g(!0), v(se, null, de(f.value, (n) => (g(), v("div", {
1348
+ key: n.id,
1349
+ class: B(["vpe-tab", { "vpe-tab--active": n.id === y.value.id }]),
980
1350
  role: "tab",
981
1351
  tabindex: "0",
982
- "aria-selected": r.id === c.value.id,
983
- "data-file-id": r.id,
984
- title: r.name,
985
- onClick: (l) => T(r.id),
986
- onKeydown: (l) => Ye(l, r)
1352
+ "aria-selected": n.id === y.value.id,
1353
+ "data-file-id": n.id,
1354
+ title: n.name,
1355
+ onClick: (l) => q(n.id),
1356
+ onKeydown: (l) => Ot(l, n)
987
1357
  }, [
988
- p("span", {
989
- class: V(["vpe-tab-dot", `vpe-tab-dot--${r.language}`]),
1358
+ c("span", {
1359
+ class: B(["vpe-tab-dot", `vpe-tab-dot--${n.language}`]),
990
1360
  "aria-hidden": "true"
991
1361
  }, null, 2),
992
- p("span", ln, J(r.name), 1),
993
- f.value.length > 1 ? (v(), b("button", {
1362
+ c("span", _n, W(n.name), 1),
1363
+ f.value.length > 1 ? (g(), v("button", {
994
1364
  key: 0,
995
1365
  class: "vpe-tab-close",
996
1366
  type: "button",
997
- title: `关闭 ${r.name}`,
998
- "aria-label": `关闭 ${r.name}`,
999
- disabled: s.readOnly,
1000
- onClick: ct((l) => Se(r.id), ["stop"])
1367
+ title: `关闭 ${n.name}`,
1368
+ "aria-label": `关闭 ${n.name}`,
1369
+ disabled: u.readOnly,
1370
+ onClick: Vt((l) => Te(n.id), ["stop"])
1001
1371
  }, [
1002
- $(S(Jt))
1003
- ], 8, un)) : G("", !0)
1004
- ], 42, sn))), 128)),
1005
- p("button", {
1372
+ $(S(Ye))
1373
+ ], 8, Dn)) : z("", !0)
1374
+ ], 42, jn))), 128)),
1375
+ c("button", {
1006
1376
  class: "vpe-tabs-add",
1007
1377
  type: "button",
1008
1378
  title: "新建文件",
1009
1379
  "aria-label": "新建文件",
1010
- disabled: s.readOnly,
1011
- onClick: ie
1380
+ disabled: u.readOnly,
1381
+ onClick: ke
1012
1382
  }, [
1013
- $(S(Gt))
1014
- ], 8, dn)
1015
- ], 512)) : G("", !0),
1016
- p("input", {
1383
+ $(S(Cn))
1384
+ ], 8, Un)
1385
+ ], 512)) : z("", !0),
1386
+ c("input", {
1017
1387
  ref_key: "fileInputEl",
1018
- ref: I,
1388
+ ref: H,
1019
1389
  class: "vpe-file-hidden",
1020
1390
  type: "file",
1021
1391
  accept: ".py,.pyw,.sql,.js,.mjs,.cjs,.jsx,.ts,.json,.txt,text/x-python,text/plain,application/json",
1022
- onChange: Ze
1392
+ onChange: Et
1023
1393
  }, null, 544),
1024
- p("div", {
1394
+ c("div", {
1025
1395
  ref_key: "editorEl",
1026
- ref: k,
1396
+ ref: P,
1027
1397
  class: "vpe-editor"
1028
1398
  }, null, 512),
1029
- s.showOutput ? (v(), b("div", {
1399
+ u.showOutput ? (g(), v("div", {
1030
1400
  key: 2,
1031
1401
  class: "vpe-output",
1032
- style: Ne({ height: _e.value })
1402
+ style: qe({ height: at.value })
1033
1403
  }, [
1034
- p("div", cn, [
1035
- t[7] || (t[7] = p("span", null, "输出", -1)),
1036
- p("button", {
1404
+ c("div", Vn, [
1405
+ t[9] || (t[9] = c("span", null, "输出", -1)),
1406
+ c("button", {
1037
1407
  class: "vpe-btn vpe-btn--sm",
1038
1408
  type: "button",
1039
1409
  title: "清空输出",
1040
- onClick: Ee
1410
+ onClick: He
1041
1411
  }, [
1042
- $(S(je))
1412
+ $(S(Ze))
1043
1413
  ])
1044
1414
  ]),
1045
- p("pre", {
1415
+ c("pre", {
1046
1416
  ref_key: "outputEl",
1047
1417
  ref: w,
1048
1418
  class: "vpe-output-body"
1049
1419
  }, [
1050
- x.value.length ? (v(!0), b(se, { key: 0 }, le(x.value, (r) => (v(), b("span", {
1051
- key: r.id,
1052
- class: V(["vpe-line", `vpe-line--${r.stream}`])
1053
- }, J(r.text) + `
1054
- `, 3))), 128)) : (v(), b("span", pn, "暂无输出,点击“运行”或按 Ctrl+Enter 执行代码"))
1420
+ C.value.length ? (g(!0), v(se, { key: 0 }, de(C.value, (n) => (g(), v("span", {
1421
+ key: n.id,
1422
+ class: B(["vpe-line", `vpe-line--${n.stream}`])
1423
+ }, W(n.text) + `
1424
+ `, 3))), 128)) : (g(), v("span", Bn, "暂无输出,点击“运行”或按 Ctrl+Enter 执行代码"))
1055
1425
  ], 512)
1056
- ], 4)) : G("", !0)
1426
+ ], 4)) : z("", !0),
1427
+ D.value ? (g(), v("div", zn, [
1428
+ c("div", Kn, [
1429
+ t[10] || (t[10] = c("span", { class: "vpe-fs-title" }, "虚拟文件", -1)),
1430
+ t[11] || (t[11] = c("span", {
1431
+ class: "vpe-spacer",
1432
+ "aria-hidden": "true"
1433
+ }, null, -1)),
1434
+ c("button", {
1435
+ class: "vpe-btn vpe-btn--sm",
1436
+ type: "button",
1437
+ title: "刷新文件列表",
1438
+ disabled: N.value,
1439
+ onClick: Ue
1440
+ }, " 刷新 ", 8, An),
1441
+ c("button", {
1442
+ class: "vpe-btn vpe-btn--sm",
1443
+ type: "button",
1444
+ title: "关闭虚拟文件面板",
1445
+ "aria-label": "关闭虚拟文件面板",
1446
+ onClick: t[1] || (t[1] = (n) => D.value = !1)
1447
+ }, [
1448
+ $(S(Ye))
1449
+ ])
1450
+ ]),
1451
+ c("div", qn, [
1452
+ N.value ? (g(), v("div", Wn, "正在读取虚拟文件…")) : (g(), v(se, { key: 1 }, [
1453
+ j.value.length ? z("", !0) : (g(), v("div", Jn, " 暂无文件。运行 Python 代码创建文件后再刷新。 ")),
1454
+ (g(!0), v(se, null, de(j.value, (n) => (g(), v("div", {
1455
+ key: n.path,
1456
+ class: B(["vpe-fs-item", { "vpe-fs-item--dir": n.isDirectory }])
1457
+ }, [
1458
+ c("span", {
1459
+ class: "vpe-fs-name",
1460
+ title: n.path
1461
+ }, W(n.path), 9, Zn),
1462
+ c("span", Gn, W(n.isDirectory ? "目录" : bt(n.size)), 1),
1463
+ n.isDirectory ? z("", !0) : (g(), v("button", {
1464
+ key: 0,
1465
+ class: "vpe-btn vpe-btn--sm",
1466
+ type: "button",
1467
+ title: `下载 ${n.name}`,
1468
+ "aria-label": `下载 ${n.name}`,
1469
+ onClick: (l) => Ve(n.path)
1470
+ }, [
1471
+ $(S(Xe))
1472
+ ], 8, Xn))
1473
+ ], 2))), 128))
1474
+ ], 64))
1475
+ ])
1476
+ ])) : z("", !0)
1057
1477
  ], 6));
1058
1478
  }
1059
1479
  });
1060
- function Ln(s = {}) {
1061
- const n = ze(s.pyodideUrl ? { pyodideUrl: s.pyodideUrl } : void 0), a = O(n.status), o = O(""), i = O([]);
1062
- let k = 0;
1063
- const w = (E, h) => {
1064
- i.value.push({ id: ++k, stream: E, text: h });
1065
- }, L = n.on("status", (E, h) => {
1066
- a.value = E, h && (o.value = h);
1067
- }), I = n.on("initError", (E) => {
1068
- w("system", `[pyodide] 加载失败:${E}`);
1480
+ function pr(u = {}) {
1481
+ var G;
1482
+ const r = nt(u.pyodideUrl ? { pyodideUrl: u.pyodideUrl } : void 0), a = F(r.status), i = F(""), s = F([]);
1483
+ let P = 0;
1484
+ const w = (o, h) => {
1485
+ s.value.push({ id: ++P, stream: o, text: h });
1486
+ }, I = r.on("status", (o, h) => {
1487
+ a.value = o, h && (i.value = h);
1488
+ }), H = r.on("initError", (o) => {
1489
+ w("system", `[pyodide] 加载失败:${o}`);
1069
1490
  });
1070
- return pt(() => {
1071
- L(), I();
1072
- }), s.preload && n.waitReady().catch(() => {
1491
+ Bt(() => {
1492
+ I(), H();
1493
+ });
1494
+ const C = async (o, h = {}) => {
1495
+ var x;
1496
+ try {
1497
+ const O = await r.run(o, {
1498
+ stdin: h.stdin,
1499
+ onOutput: (U, X) => w(U, X)
1500
+ });
1501
+ return !O.ok && ((x = O.error) != null && x.traceback) && w("stderr", O.error.traceback), O;
1502
+ } catch (O) {
1503
+ return {
1504
+ ok: !1,
1505
+ durationMs: 0,
1506
+ error: { type: "RuntimeError", message: O instanceof Error ? O.message : String(O), traceback: "" }
1507
+ };
1508
+ }
1509
+ }, M = async (o, h) => {
1510
+ try {
1511
+ return await r.writeFile(o, h);
1512
+ } catch (x) {
1513
+ return { ok: !1, error: { type: "RuntimeError", message: x instanceof Error ? x.message : String(x), traceback: "" } };
1514
+ }
1515
+ }, T = async (o) => {
1516
+ try {
1517
+ return await r.readFile(o);
1518
+ } catch (h) {
1519
+ return { ok: !1, error: { type: "RuntimeError", message: h instanceof Error ? h.message : String(h), traceback: "" } };
1520
+ }
1521
+ }, D = async (o = ".") => {
1522
+ try {
1523
+ return await r.listFiles(o);
1524
+ } catch (h) {
1525
+ return { ok: !1, error: { type: "RuntimeError", message: h instanceof Error ? h.message : String(h), traceback: "" } };
1526
+ }
1527
+ }, N = async (o) => {
1528
+ try {
1529
+ return await r.loadPackages(o, { onOutput: (h, x) => w(h, x) });
1530
+ } catch (h) {
1531
+ return {
1532
+ ok: !1,
1533
+ durationMs: 0,
1534
+ error: { type: "RuntimeError", message: h instanceof Error ? h.message : String(h), traceback: "" }
1535
+ };
1536
+ }
1537
+ };
1538
+ let j = !1;
1539
+ const J = async () => {
1540
+ var x;
1541
+ if (j) return;
1542
+ const o = u.preloadPackages ?? [];
1543
+ if (!o.length) return;
1544
+ j = !0, w("system", `[pyodide] 正在安装预置包:${o.join(", ")}`);
1545
+ const h = await N(o);
1546
+ w(
1547
+ "system",
1548
+ h.ok ? `[pyodide] 预置包安装完成(${(h.durationMs / 1e3).toFixed(1)}s)` : `[pyodide] 预置包安装失败:${((x = h.error) == null ? void 0 : x.message) ?? "未知错误"}`
1549
+ );
1550
+ };
1551
+ return (u.preload || (((G = u.preloadPackages) == null ? void 0 : G.length) ?? 0) > 0) && r.waitReady().then(() => J()).catch(() => {
1073
1552
  }), {
1074
1553
  status: a,
1075
- version: o,
1076
- outputs: i,
1077
- runPython: async (E) => {
1078
- try {
1079
- return await n.run(E, { onOutput: (h, M) => w(h, M) });
1080
- } catch (h) {
1081
- return {
1082
- ok: !1,
1083
- durationMs: 0,
1084
- error: { type: "RuntimeError", message: h instanceof Error ? h.message : String(h), traceback: "" }
1085
- };
1086
- }
1087
- },
1088
- install: async (E) => {
1089
- try {
1090
- return await n.loadPackages(E, { onOutput: (h, M) => w(h, M) });
1091
- } catch (h) {
1092
- return {
1093
- ok: !1,
1094
- durationMs: 0,
1095
- error: { type: "RuntimeError", message: h instanceof Error ? h.message : String(h), traceback: "" }
1096
- };
1097
- }
1098
- },
1099
- checkSyntax: (E) => n.checkSyntax(E),
1100
- interrupt: () => n.interrupt(),
1554
+ version: i,
1555
+ outputs: s,
1556
+ runPython: C,
1557
+ install: N,
1558
+ checkSyntax: (o) => r.checkSyntax(o),
1559
+ interrupt: () => r.interrupt(),
1101
1560
  clearOutputs: () => {
1102
- i.value = [];
1561
+ s.value = [];
1103
1562
  },
1563
+ writeFile: M,
1564
+ readFile: T,
1565
+ listFiles: D,
1104
1566
  /** 预加载并在就绪后 resolve */
1105
- ready: () => n.waitReady()
1567
+ ready: () => r.waitReady()
1106
1568
  };
1107
1569
  }
1108
- const Fn = fn;
1570
+ const fr = Yn;
1109
1571
  export {
1110
- Ve as DEFAULT_PYODIDE_URL,
1111
- $t as MONO_FONT_STACK,
1112
- Vt as PyodideRunner,
1113
- Fn as PythonEditor,
1114
- Rt as createEditor,
1115
- fn as default,
1116
- ze as getRunner,
1117
- jt as makePythonLinter,
1118
- Ue as setErrorLines,
1119
- Ln as usePyodide
1572
+ tt as DEFAULT_PYODIDE_URL,
1573
+ cn as MONO_FONT_STACK,
1574
+ kn as PyodideRunner,
1575
+ fr as PythonEditor,
1576
+ mn as createEditor,
1577
+ Yn as default,
1578
+ nt as getRunner,
1579
+ yn as makePythonLinter,
1580
+ et as setErrorLines,
1581
+ pr as usePyodide
1120
1582
  };