@innovatorved/code-lab 0.2.0 → 0.3.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.
Files changed (66) hide show
  1. package/ARCHITECTURE.md +11 -6
  2. package/CHANGELOG.md +40 -0
  3. package/README.md +18 -8
  4. package/dist/code-lab.css +198 -0
  5. package/dist/code-lab.d.ts +27 -9
  6. package/dist/code-lab.esm.js +8516 -84
  7. package/dist/code-lab.js +8514 -82
  8. package/dist/extensions/cpp.d.ts +40 -6
  9. package/dist/extensions/cpp.esm.js +1027 -7
  10. package/dist/extensions/cpp.js +1027 -7
  11. package/dist/extensions/guided-lab.esm.js +40 -2
  12. package/dist/extensions/guided-lab.js +40 -2
  13. package/dist/extensions/python.d.ts +92 -0
  14. package/dist/extensions/python.esm.js +5476 -0
  15. package/dist/extensions/python.js +5495 -0
  16. package/dist/index.d.ts +7 -4
  17. package/dist/preview-sw.js +1 -1
  18. package/dist/runtime/index.d.ts +4 -0
  19. package/dist/runtime/test-harness.d.ts +24 -0
  20. package/dist/runtime.esm.js +36 -4
  21. package/dist/runtime.js +36 -4
  22. package/dist/schemas.d.ts +137 -24
  23. package/dist/schemas.esm.js +44 -2
  24. package/dist/schemas.js +44 -2
  25. package/dist/shell/coreutils/compilers-cli.d.ts +24 -0
  26. package/dist/shell/index.d.ts +4 -0
  27. package/dist/shell.esm.js +113 -1
  28. package/dist/shell.js +113 -1
  29. package/dist/terminal.esm.js +1 -1
  30. package/dist/terminal.js +1 -1
  31. package/dist/workbench/command-palette.d.ts +10 -0
  32. package/dist/workbench/diff-editor.d.ts +26 -0
  33. package/dist/workbench/drawer.d.ts +18 -0
  34. package/dist/workbench/editor.d.ts +11 -0
  35. package/dist/workbench/file-tree.d.ts +11 -0
  36. package/dist/workbench/guided-pane.d.ts +11 -0
  37. package/dist/workbench/icons.d.ts +5 -0
  38. package/dist/workbench/index.d.ts +39 -0
  39. package/dist/workbench/share.d.ts +21 -0
  40. package/dist/workbench/styles.d.ts +4 -0
  41. package/dist/workbench/toolbar.d.ts +17 -0
  42. package/dist/workbench.d.ts +6 -1
  43. package/package.json +8 -2
  44. package/src/code-lab.css +198 -0
  45. package/src/extensions/cpp.ts +966 -5
  46. package/src/extensions/python.ts +1293 -0
  47. package/src/index.ts +35 -3
  48. package/src/runtime/index.ts +5 -0
  49. package/src/runtime/test-harness.ts +57 -0
  50. package/src/runtime.ts +35 -3
  51. package/src/schemas.ts +47 -2
  52. package/src/shell/coreutils/compilers-cli.ts +103 -0
  53. package/src/shell/index.ts +5 -0
  54. package/src/shell.ts +112 -0
  55. package/src/workbench/command-palette.ts +140 -0
  56. package/src/workbench/diff-editor.ts +216 -0
  57. package/src/workbench/drawer.ts +144 -0
  58. package/src/workbench/editor.ts +49 -0
  59. package/src/workbench/file-tree.ts +51 -0
  60. package/src/workbench/guided-pane.ts +33 -0
  61. package/src/workbench/icons.ts +48 -0
  62. package/src/workbench/index.ts +38 -0
  63. package/src/workbench/share.ts +99 -0
  64. package/src/workbench/styles.ts +200 -0
  65. package/src/workbench/toolbar.ts +171 -0
  66. package/src/workbench.ts +744 -69
@@ -0,0 +1,1293 @@
1
+ import { PythonExtensionOptions, PythonExtensionOptionsSchema, PythonToolchainProgress } from '../schemas';
2
+ import type { DiagnosticItem } from '../diagnostics';
3
+ import { CodeLabTestParser, type TestResultItem } from '../runtime/test-harness';
4
+
5
+ export const DEFAULT_PYTHON_CDN_BASE_URL = 'https://cdn.jsdelivr.net/pyodide/v0.27.2/full/';
6
+
7
+ export const PYTHON_TOOLCHAIN_PRESETS = {
8
+ latest: 'https://cdn.jsdelivr.net/pyodide/v0.27.2/full/',
9
+ v0_26: 'https://cdn.jsdelivr.net/pyodide/v0.26.4/full/'
10
+ };
11
+
12
+ /**
13
+ * Built-in Python modules seeded into `/usr/lib/python` inside the VirtualFS.
14
+ */
15
+ export const BUILTIN_PYTHON_MODULES: Record<string, string> = {
16
+ '/usr/lib/python/codelab_dsa.py': `# CodeLab <codelab_dsa.py> - Data Structures & Algorithms Utilities
17
+ from typing import Optional, List, Any
18
+
19
+ class ListNode:
20
+ def __init__(self, val: int = 0, next: Optional['ListNode'] = None):
21
+ self.val = val
22
+ self.next = next
23
+
24
+ def __repr__(self):
25
+ vals = []
26
+ curr = self
27
+ while curr and len(vals) < 50:
28
+ vals.append(str(curr.val))
29
+ curr = curr.next
30
+ if curr:
31
+ vals.append("...")
32
+ return "[" + " -> ".join(vals) + "]"
33
+
34
+ class TreeNode:
35
+ def __init__(self, val: int = 0, left: Optional['TreeNode'] = None, right: Optional['TreeNode'] = None):
36
+ self.val = val
37
+ self.left = left
38
+ self.right = right
39
+
40
+ def __repr__(self):
41
+ return f"TreeNode({self.val})"
42
+
43
+ def build_linked_list(vals: List[int]) -> Optional[ListNode]:
44
+ if not vals:
45
+ return None
46
+ dummy = ListNode(0)
47
+ tail = dummy
48
+ for v in vals:
49
+ tail.next = ListNode(v)
50
+ tail = tail.next
51
+ return dummy.next
52
+
53
+ def linked_list_to_list(head: Optional[ListNode]) -> List[int]:
54
+ out = []
55
+ curr = head
56
+ while curr is not None:
57
+ out.append(curr.val)
58
+ curr = curr.next
59
+ return out
60
+
61
+ def build_binary_tree(vals: List[Optional[int]]) -> Optional[TreeNode]:
62
+ if not vals or vals[0] is None:
63
+ return None
64
+ root = TreeNode(vals[0])
65
+ queue = [root]
66
+ i = 1
67
+ while queue and i < len(vals):
68
+ curr = queue.pop(0)
69
+ if i < len(vals) and vals[i] is not None:
70
+ curr.left = TreeNode(vals[i])
71
+ queue.append(curr.left)
72
+ i += 1
73
+ if i < len(vals) and vals[i] is not None:
74
+ curr.right = TreeNode(vals[i])
75
+ queue.append(curr.right)
76
+ i += 1
77
+ return root
78
+
79
+ def binary_tree_to_list(root: Optional[TreeNode]) -> List[Optional[int]]:
80
+ if not root:
81
+ return []
82
+ out = []
83
+ queue = [root]
84
+ while queue:
85
+ curr = queue.pop(0)
86
+ if curr is not None:
87
+ out.append(curr.val)
88
+ queue.append(curr.left)
89
+ queue.append(curr.right)
90
+ else:
91
+ out.append(None)
92
+ while out and out[-1] is None:
93
+ out.pop()
94
+ return out
95
+
96
+ import heapq
97
+
98
+ class MinHeap:
99
+ def __init__(self, items: Optional[List[Any]] = None):
100
+ self._data = list(items) if items else []
101
+ heapq.heapify(self._data)
102
+
103
+ def push(self, val: Any):
104
+ heapq.heappush(self._data, val)
105
+
106
+ def pop(self) -> Any:
107
+ return heapq.heappop(self._data)
108
+
109
+ def peek(self) -> Optional[Any]:
110
+ return self._data[0] if self._data else None
111
+
112
+ def __len__(self) -> int:
113
+ return len(self._data)
114
+
115
+ class MaxHeap:
116
+ def __init__(self, items: Optional[List[Any]] = None):
117
+ self._data = [-x for x in items] if items else []
118
+ heapq.heapify(self._data)
119
+
120
+ def push(self, val: Any):
121
+ heapq.heappush(self._data, -val)
122
+
123
+ def pop(self) -> Any:
124
+ return -heapq.heappop(self._data)
125
+
126
+ def peek(self) -> Optional[Any]:
127
+ return -self._data[0] if self._data else None
128
+
129
+ def __len__(self) -> int:
130
+ return len(self._data)
131
+ `,
132
+
133
+ '/usr/lib/python/codelab_test.py': `# CodeLab <codelab_test.py> - Structured Test Harness
134
+ import json
135
+ import time
136
+ import sys
137
+ import traceback
138
+ from typing import Any, Callable
139
+
140
+ _SUITE_NAME = "Default Test Suite"
141
+ _PASSED_COUNT = 0
142
+ _FAILED_COUNT = 0
143
+ _TOTAL_COUNT = 0
144
+
145
+ def DESCRIBE(name: str):
146
+ global _SUITE_NAME
147
+ _SUITE_NAME = str(name)
148
+
149
+ def TEST(name: str, fn: Callable[[], Any]):
150
+ global _PASSED_COUNT, _FAILED_COUNT, _TOTAL_COUNT
151
+ _TOTAL_COUNT += 1
152
+ start = time.perf_counter()
153
+ err_obj = None
154
+ passed = False
155
+ try:
156
+ fn()
157
+ passed = True
158
+ _PASSED_COUNT += 1
159
+ except AssertionError as e:
160
+ _FAILED_COUNT += 1
161
+ msg = str(e) or "Assertion failed"
162
+ err_obj = {"name": "AssertionError", "message": msg, "stack": traceback.format_exc()}
163
+ except Exception as e:
164
+ _FAILED_COUNT += 1
165
+ err_obj = {"name": type(e).__name__, "message": str(e), "stack": traceback.format_exc()}
166
+ finally:
167
+ duration_ms = round((time.perf_counter() - start) * 1000, 2)
168
+ event = {
169
+ "name": name,
170
+ "passed": passed,
171
+ "durationMs": duration_ms,
172
+ "error": err_obj
173
+ }
174
+ print(f"__CODELAB_TEST__:{json.dumps(event)}", flush=True)
175
+
176
+ def ASSERT_TRUE(condition: bool, msg: str = "Expected condition to be True"):
177
+ if not bool(condition):
178
+ raise AssertionError(msg)
179
+
180
+ def ASSERT_FALSE(condition: bool, msg: str = "Expected condition to be False"):
181
+ if bool(condition):
182
+ raise AssertionError(msg)
183
+
184
+ def ASSERT_EQ(actual: Any, expected: Any, msg: str = None):
185
+ if actual != expected:
186
+ err = msg or f"Assertion failed: expected {expected!r}, got {actual!r}"
187
+ raise AssertionError(err)
188
+
189
+ def ASSERT_NE(actual: Any, expected: Any, msg: str = None):
190
+ if actual == expected:
191
+ err = msg or f"Assertion failed: expected value not equal to {expected!r}"
192
+ raise AssertionError(err)
193
+
194
+ def CODELAB_TEST_EXIT_CODE() -> int:
195
+ return 0 if _FAILED_COUNT == 0 else 1
196
+
197
+ from contextlib import contextmanager
198
+
199
+ @contextmanager
200
+ def describe(name: str):
201
+ DESCRIBE(name)
202
+ yield
203
+
204
+ @contextmanager
205
+ def it(name: str):
206
+ global _TOTAL_COUNT, _PASSED_COUNT, _FAILED_COUNT
207
+ _TOTAL_COUNT += 1
208
+ start = time.perf_counter()
209
+ passed = False
210
+ err_obj = None
211
+ try:
212
+ yield
213
+ passed = True
214
+ _PASSED_COUNT += 1
215
+ except AssertionError as e:
216
+ _FAILED_COUNT += 1
217
+ err_obj = {"name": "AssertionError", "message": str(e) or "Assertion failed", "stack": traceback.format_exc()}
218
+ except Exception as e:
219
+ _FAILED_COUNT += 1
220
+ err_obj = {"name": type(e).__name__, "message": str(e), "stack": traceback.format_exc()}
221
+ finally:
222
+ duration_ms = round((time.perf_counter() - start) * 1000, 2)
223
+ event = {"name": name, "passed": passed, "durationMs": duration_ms, "error": err_obj}
224
+ print(f"__CODELAB_TEST__:{json.dumps(event)}", flush=True)
225
+
226
+ test = it
227
+ assert_equal = ASSERT_EQ
228
+ assert_true = ASSERT_TRUE
229
+ assert_false = ASSERT_FALSE
230
+ `
231
+ };
232
+
233
+ export const CODELAB_PYTHON_LIBS = BUILTIN_PYTHON_MODULES;
234
+
235
+ export interface ExtendedPythonExtensionOptions extends PythonExtensionOptions {
236
+ [key: string]: any;
237
+ }
238
+
239
+ export interface PythonCompileResult {
240
+ ok: boolean;
241
+ exitCode: number;
242
+ stdout: string;
243
+ stderr: string;
244
+ peakMemoryBytes: number;
245
+ durationMs: number;
246
+ testResults?: TestResultItem[];
247
+ }
248
+
249
+ export interface PythonSymbolDoc {
250
+ label: string;
251
+ kind?: string;
252
+ detail: string;
253
+ documentation: string;
254
+ insertText?: string;
255
+ module?: string;
256
+ complexity?: string;
257
+ }
258
+
259
+ export const PYTHON_COMPLETIONS_AND_HOVERS: Record<string, PythonSymbolDoc> = {
260
+ 'collections.deque': {
261
+ label: 'collections.deque',
262
+ detail: 'class collections.deque([iterable[, maxlen]])',
263
+ documentation: 'Double-ended queue with $O(1)$ appends and pops from either end.\n\n- Module: `collections`\n- append/pop/appendleft/popleft: $O(1)$',
264
+ insertText: 'from collections import deque\n${1:dq} = deque()',
265
+ module: 'collections',
266
+ complexity: 'O(1) end operations'
267
+ },
268
+ 'collections.defaultdict': {
269
+ label: 'collections.defaultdict',
270
+ detail: 'class collections.defaultdict(default_factory=None, /[, ...])',
271
+ documentation: 'Dict subclass that calls a factory function to supply missing values.\n\n- Module: `collections`',
272
+ insertText: 'from collections import defaultdict\n${1:d} = defaultdict(${2:list})',
273
+ module: 'collections',
274
+ complexity: 'O(1) average lookup'
275
+ },
276
+ 'collections.Counter': {
277
+ label: 'collections.Counter',
278
+ detail: 'class collections.Counter([iterable-or-mapping])',
279
+ documentation: 'Dict subclass for counting hashable items.\n\n- Module: `collections`',
280
+ insertText: 'from collections import Counter\n${1:counts} = Counter(${2:items})',
281
+ module: 'collections',
282
+ complexity: 'O(N) initialization'
283
+ },
284
+ 'heapq.heappush': {
285
+ label: 'heapq.heappush',
286
+ detail: 'heapq.heappush(heap, item)',
287
+ documentation: 'Pushes item onto heap, maintaining the min-heap invariant.\n\n- Module: `heapq`\n- Complexity: $O(\\log N)$',
288
+ insertText: 'heapq.heappush(${1:heap}, ${2:item})',
289
+ module: 'heapq',
290
+ complexity: 'O(log N)'
291
+ },
292
+ 'heapq.heappop': {
293
+ label: 'heapq.heappop',
294
+ detail: 'heapq.heappop(heap)',
295
+ documentation: 'Pops and returns the smallest item from heap, maintaining invariant.\n\n- Module: `heapq`\n- Complexity: $O(\\log N)$',
296
+ insertText: 'heapq.heappop(${1:heap})',
297
+ module: 'heapq',
298
+ complexity: 'O(log N)'
299
+ },
300
+ 'bisect.bisect_left': {
301
+ label: 'bisect.bisect_left',
302
+ detail: 'bisect.bisect_left(a, x, lo=0, hi=len(a))',
303
+ documentation: 'Locates the insertion point for x in a to maintain sorted order (leftmost index).\n\n- Module: `bisect`\n- Complexity: $O(\\log N)$',
304
+ insertText: 'bisect.bisect_left(${1:a}, ${2:x})',
305
+ module: 'bisect',
306
+ complexity: 'O(log N)'
307
+ },
308
+ 'functools.lru_cache': {
309
+ label: 'functools.lru_cache',
310
+ detail: '@functools.lru_cache(maxsize=128, typed=False)',
311
+ documentation: 'Decorator to wrap a function with a memoizing callable that saves up to maxsize results.\n\n- Module: `functools`',
312
+ insertText: '@lru_cache(maxsize=None)\ndef ${1:fn}(${2:args}):\n pass',
313
+ module: 'functools',
314
+ complexity: 'O(1) cached lookup'
315
+ },
316
+ 'codelab_dsa.ListNode': {
317
+ label: 'ListNode',
318
+ detail: 'class ListNode(val=0, next=None)',
319
+ documentation: 'LeetCode / DSA standard singly-linked list node.\n\n- Module: `codelab_dsa`',
320
+ insertText: 'ListNode(${1:val})',
321
+ module: 'codelab_dsa',
322
+ complexity: 'O(1)'
323
+ },
324
+ 'codelab_dsa.TreeNode': {
325
+ label: 'TreeNode',
326
+ detail: 'class TreeNode(val=0, left=None, right=None)',
327
+ documentation: 'LeetCode / DSA standard binary tree node.\n\n- Module: `codelab_dsa`',
328
+ insertText: 'TreeNode(${1:val})',
329
+ module: 'codelab_dsa',
330
+ complexity: 'O(1)'
331
+ },
332
+ 'codelab_dsa.build_linked_list': {
333
+ label: 'build_linked_list',
334
+ detail: 'build_linked_list(vals: list[int]) -> Optional[ListNode]',
335
+ documentation: 'Builds a singly-linked list from a Python list of integers.\n\n- Module: `codelab_dsa`\n- Complexity: $O(N)$',
336
+ insertText: 'build_linked_list([${1:1, 2, 3}])',
337
+ module: 'codelab_dsa',
338
+ complexity: 'O(N)'
339
+ },
340
+ 'codelab_dsa.linked_list_to_list': {
341
+ label: 'linked_list_to_list',
342
+ detail: 'linked_list_to_list(head: Optional[ListNode]) -> list[int]',
343
+ documentation: 'Traverses a linked list and collects values into a Python list.\n\n- Module: `codelab_dsa`\n- Complexity: $O(N)$',
344
+ insertText: 'linked_list_to_list(${1:head})',
345
+ module: 'codelab_dsa',
346
+ complexity: 'O(N)'
347
+ },
348
+ 'codelab_dsa.build_binary_tree': {
349
+ label: 'build_binary_tree',
350
+ detail: 'build_binary_tree(vals: list[Optional[int]]) -> Optional[TreeNode]',
351
+ documentation: 'Constructs a binary tree level-by-level from a list containing None for null nodes.\n\n- Module: `codelab_dsa`\n- Complexity: $O(N)$',
352
+ insertText: 'build_binary_tree([${1:1, 2, 3}])',
353
+ module: 'codelab_dsa',
354
+ complexity: 'O(N)'
355
+ },
356
+ 'codelab_test.DESCRIBE': {
357
+ label: 'DESCRIBE',
358
+ detail: 'DESCRIBE(name: str)',
359
+ documentation: 'Defines the active test suite description in CodeLab test harness.\n\n- Module: `codelab_test`',
360
+ insertText: 'DESCRIBE("${1:Suite Name}")\n',
361
+ module: 'codelab_test',
362
+ complexity: 'Test Suite Header'
363
+ },
364
+ 'codelab_test.TEST': {
365
+ label: 'TEST',
366
+ detail: 'TEST(name: str, fn: Callable)',
367
+ documentation: 'Runs a single test case; emits structured __CODELAB_TEST__ telemetry.\n\n- Module: `codelab_test`',
368
+ insertText: 'def test_${1:case}():\n ASSERT_EQ(${2:actual}, ${3:expected})\n\nTEST("${4:description}", test_${1:case})',
369
+ module: 'codelab_test',
370
+ complexity: 'Test Case Runner'
371
+ },
372
+ 'codelab_test.ASSERT_EQ': {
373
+ label: 'ASSERT_EQ',
374
+ detail: 'ASSERT_EQ(actual, expected, msg=None)',
375
+ documentation: 'Asserts that actual == expected; logs failure message if not.\n\n- Module: `codelab_test`',
376
+ insertText: 'ASSERT_EQ(${1:actual}, ${2:expected})',
377
+ module: 'codelab_test',
378
+ complexity: 'Assertion'
379
+ },
380
+ 'codelab_test.ASSERT_TRUE': {
381
+ label: 'ASSERT_TRUE',
382
+ detail: 'ASSERT_TRUE(condition, msg=None)',
383
+ documentation: 'Asserts condition is True.\n\n- Module: `codelab_test`',
384
+ insertText: 'ASSERT_TRUE(${1:condition})',
385
+ module: 'codelab_test',
386
+ complexity: 'Assertion'
387
+ },
388
+ 'codelab_test.ASSERT_FALSE': {
389
+ label: 'ASSERT_FALSE',
390
+ detail: 'ASSERT_FALSE(condition, msg=None)',
391
+ documentation: 'Asserts condition is False.\n\n- Module: `codelab_test`',
392
+ insertText: 'ASSERT_FALSE(${1:condition})',
393
+ module: 'codelab_test',
394
+ complexity: 'Assertion'
395
+ },
396
+ 'codelab_test.CODELAB_TEST_EXIT_CODE': {
397
+ label: 'CODELAB_TEST_EXIT_CODE',
398
+ detail: 'CODELAB_TEST_EXIT_CODE() -> int',
399
+ documentation: 'Returns 0 if all tests passed, 1 if any failed.\n\n- Module: `codelab_test`',
400
+ insertText: 'sys.exit(CODELAB_TEST_EXIT_CODE())',
401
+ module: 'codelab_test',
402
+ complexity: 'Exit Code'
403
+ }
404
+ };
405
+
406
+ let _monacoPyRegistered = false;
407
+
408
+ /**
409
+ * Registers Monaco Python completion and hover providers.
410
+ */
411
+ export function registerMonacoPythonLanguageService(monacoInstance: any): boolean {
412
+ if (!monacoInstance || !monacoInstance.languages) return false;
413
+ if (_monacoPyRegistered) return true;
414
+ _monacoPyRegistered = true;
415
+
416
+ try {
417
+ monacoInstance.languages.registerCompletionItemProvider('python', {
418
+ triggerCharacters: ['.'],
419
+ provideCompletionItems(model: any, position: any) {
420
+ const wordInfo = model.getWordUntilPosition(position);
421
+ const range = {
422
+ startLineNumber: position.lineNumber,
423
+ endLineNumber: position.lineNumber,
424
+ startColumn: wordInfo.startColumn,
425
+ endColumn: wordInfo.endColumn
426
+ };
427
+
428
+ const suggestions = Object.keys(PYTHON_COMPLETIONS_AND_HOVERS).map((key) => {
429
+ const item = PYTHON_COMPLETIONS_AND_HOVERS[key];
430
+ return {
431
+ label: item.label,
432
+ kind: monacoInstance.languages.CompletionItemKind.Function,
433
+ detail: item.detail,
434
+ documentation: { value: item.documentation },
435
+ insertText: item.insertText || item.label,
436
+ insertTextRules: monacoInstance.languages.CompletionItemInsertTextRule.InsertAsSnippet,
437
+ range
438
+ };
439
+ });
440
+
441
+ return { suggestions };
442
+ }
443
+ });
444
+
445
+ monacoInstance.languages.registerHoverProvider('python', {
446
+ provideHover(model: any, position: any) {
447
+ const word = model.getWordAtPosition(position);
448
+ if (!word) return null;
449
+
450
+ let item: PythonSymbolDoc | null = null;
451
+ for (const k of Object.keys(PYTHON_COMPLETIONS_AND_HOVERS)) {
452
+ if (k === word.word || k.endsWith('.' + word.word)) {
453
+ item = PYTHON_COMPLETIONS_AND_HOVERS[k];
454
+ break;
455
+ }
456
+ }
457
+ if (!item) return null;
458
+
459
+ return {
460
+ range: {
461
+ startLineNumber: position.lineNumber,
462
+ endLineNumber: position.lineNumber,
463
+ startColumn: word.startColumn,
464
+ endColumn: word.endColumn
465
+ },
466
+ contents: [
467
+ { value: `**${item.label}** — \`${item.detail}\`` },
468
+ { value: item.documentation }
469
+ ]
470
+ };
471
+ }
472
+ });
473
+ return true;
474
+ } catch (err) {
475
+ if (typeof console !== 'undefined' && console.warn) {
476
+ console.warn('[Python Monaco Intelligence Error]:', err);
477
+ }
478
+ return false;
479
+ }
480
+ }
481
+
482
+ /**
483
+ * Tier-1 instant Python static AST and syntax checker.
484
+ */
485
+ export function analyzePythonSource(source: string, filename = 'main.py'): DiagnosticItem[] {
486
+ const diagnostics: DiagnosticItem[] = [];
487
+ if (!source || typeof source !== 'string') return diagnostics;
488
+
489
+ const lines = source.split('\n');
490
+
491
+ // 1. Bracket stack matching
492
+ const stack: Array<{ char: string; line: number; col: number }> = [];
493
+ const matching: Record<string, string> = { ')': '(', ']': '[', '}': '{' };
494
+
495
+ let expectIndentAfterLine = 0;
496
+ let expectIndentMin = 0;
497
+
498
+ for (let l = 0; l < lines.length; l++) {
499
+ const line = lines[l];
500
+ const lineNum = l + 1;
501
+ let inStr = false;
502
+ let strChar = '';
503
+
504
+ // Check mixed tab and space indentation
505
+ const indentMatch = line.match(/^([ \t]+)/);
506
+ const indentLen = indentMatch ? indentMatch[1].length : 0;
507
+ if (indentMatch) {
508
+ const indent = indentMatch[1];
509
+ if (indent.includes('\t') && indent.includes(' ')) {
510
+ diagnostics.push({
511
+ id: `py-tab-space-mix-${lineNum}`,
512
+ file: filename,
513
+ line: lineNum,
514
+ startLineNumber: lineNum,
515
+ col: 1,
516
+ startColumn: 1,
517
+ severity: 'warning',
518
+ message: 'Inconsistent use of tabs and spaces in indentation.',
519
+ source: 'python-linter'
520
+ } as any);
521
+ }
522
+ }
523
+
524
+ const trimmed = line.trim();
525
+
526
+ // Check expected indentation after ':'
527
+ if (expectIndentAfterLine > 0 && trimmed && !trimmed.startsWith('#')) {
528
+ if (indentLen <= expectIndentMin) {
529
+ diagnostics.push({
530
+ id: `py-indent-error-${lineNum}`,
531
+ file: filename,
532
+ line: lineNum,
533
+ startLineNumber: lineNum,
534
+ col: 1,
535
+ startColumn: 1,
536
+ severity: 'error',
537
+ message: `IndentationError: expected an indented block after statement on line ${expectIndentAfterLine}.`,
538
+ source: 'python-linter'
539
+ } as any);
540
+ }
541
+ expectIndentAfterLine = 0;
542
+ }
543
+
544
+ for (let c = 0; c < line.length; c++) {
545
+ const ch = line[c];
546
+ if (!inStr && ch === '#') break; // Comment
547
+
548
+ if (ch === '"' || ch === '\'') {
549
+ if (!inStr) {
550
+ inStr = true;
551
+ strChar = ch;
552
+ } else if (strChar === ch && (c === 0 || line[c - 1] !== '\\')) {
553
+ inStr = false;
554
+ }
555
+ continue;
556
+ }
557
+
558
+ if (inStr) continue;
559
+
560
+ if (ch === '(' || ch === '[' || ch === '{') {
561
+ stack.push({ char: ch, line: lineNum, col: c + 1 });
562
+ } else if (ch === ')' || ch === ']' || ch === '}') {
563
+ const expected = matching[ch];
564
+ const last = stack.pop();
565
+ if (!last) {
566
+ diagnostics.push({
567
+ id: `py-bracket-unmatched-${lineNum}-${c + 1}`,
568
+ file: filename,
569
+ line: lineNum,
570
+ startLineNumber: lineNum,
571
+ col: c + 1,
572
+ startColumn: c + 1,
573
+ severity: 'error',
574
+ message: `Unmatched closing bracket '${ch}'.`,
575
+ source: 'python-linter'
576
+ } as any);
577
+ } else if (last.char !== expected) {
578
+ diagnostics.push({
579
+ id: `py-bracket-mismatch-${lineNum}-${c + 1}`,
580
+ file: filename,
581
+ line: lineNum,
582
+ startLineNumber: lineNum,
583
+ col: c + 1,
584
+ startColumn: c + 1,
585
+ severity: 'error',
586
+ message: `Mismatched bracket: expected closing for '${last.char}' from line ${last.line}, found '${ch}'.`,
587
+ source: 'python-linter'
588
+ } as any);
589
+ }
590
+ }
591
+ }
592
+
593
+ if (inStr && !line.includes('"""') && !line.includes("'''")) {
594
+ diagnostics.push({
595
+ id: `py-eol-string-${lineNum}`,
596
+ file: filename,
597
+ line: lineNum,
598
+ startLineNumber: lineNum,
599
+ col: line.length,
600
+ startColumn: line.length,
601
+ severity: 'error',
602
+ message: 'SyntaxError: EOL while scanning string literal.',
603
+ source: 'python-linter'
604
+ } as any);
605
+ }
606
+
607
+ // Check missing colon or setup expected indentation
608
+ if (/^(?:def\b|class\b|if\b|elif\b|else\b|for\b|while\b|try\b|finally\b|except\b|with\b)/.test(trimmed)) {
609
+ if (!trimmed.endsWith(':')) {
610
+ diagnostics.push({
611
+ id: `py-missing-colon-${lineNum}`,
612
+ file: filename,
613
+ line: lineNum,
614
+ startLineNumber: lineNum,
615
+ col: line.length,
616
+ startColumn: line.length,
617
+ severity: 'error',
618
+ message: `SyntaxError: expected ':' at end of line.`,
619
+ source: 'python-linter'
620
+ } as any);
621
+ } else if (trimmed.endsWith(':')) {
622
+ expectIndentAfterLine = lineNum;
623
+ expectIndentMin = indentLen;
624
+ }
625
+ }
626
+ }
627
+
628
+ for (const unclosed of stack) {
629
+ diagnostics.push({
630
+ id: `py-unclosed-bracket-${unclosed.line}-${unclosed.col}`,
631
+ file: filename,
632
+ line: unclosed.line,
633
+ startLineNumber: unclosed.line,
634
+ col: unclosed.col,
635
+ startColumn: unclosed.col,
636
+ severity: 'error',
637
+ message: `SyntaxError: closing parenthesis does not match or unclosed bracket '${unclosed.char}' opened on line ${unclosed.line}.`,
638
+ source: 'python-linter'
639
+ } as any);
640
+ }
641
+
642
+ return diagnostics;
643
+ }
644
+
645
+ /**
646
+ * Parses Python tracebacks and SyntaxErrors from stderr and pushes into DiagnosticsStore & Monaco markers.
647
+ */
648
+ export function applyPythonTracebackDiagnostics(
649
+ stderrText: string,
650
+ diagnosticsStore?: any,
651
+ monacoInstance?: any,
652
+ activeModel?: any
653
+ ): DiagnosticItem[] {
654
+ const diagnostics: DiagnosticItem[] = [];
655
+ if (!stderrText || typeof stderrText !== 'string') return diagnostics;
656
+
657
+ if (diagnosticsStore && typeof diagnosticsStore.clear === 'function') {
658
+ diagnosticsStore.clear('python');
659
+ }
660
+
661
+ // Regex matching Python File ".../workspace/<file>.py", line <N>
662
+ const tbRegex = /File\s+["'](?:(?:\/workspace\/)?([^"']+))["'],\s+line\s+(\d+)(?:,\s+in\s+([A-Za-z0-9_<>]+))?/g;
663
+ let lastFile = 'main.py';
664
+ let lastLine = 1;
665
+ let match: RegExpExecArray | null;
666
+
667
+ while ((match = tbRegex.exec(stderrText)) !== null) {
668
+ lastFile = match[1].replace(/^\/workspace\//, '');
669
+ lastLine = parseInt(match[2], 10) || 1;
670
+ }
671
+
672
+ // Look for exception line e.g. "NameError: name 'foo' is not defined" or "SyntaxError: invalid syntax"
673
+ const lines = stderrText.trim().split('\n');
674
+ const errLine = lines[lines.length - 1] || 'Python Execution Error';
675
+
676
+ if (errLine.includes('Error:') || errLine.includes('Exception:') || errLine.includes('Error')) {
677
+ const item: DiagnosticItem = {
678
+ id: `python-error-${lastFile}-${lastLine}`,
679
+ file: lastFile,
680
+ line: lastLine,
681
+ startLineNumber: lastLine,
682
+ col: 1,
683
+ startColumn: 1,
684
+ severity: 'error',
685
+ message: `[Python] ${errLine.trim()}`,
686
+ source: 'python'
687
+ } as any;
688
+ diagnostics.push(item);
689
+ if (diagnosticsStore && typeof diagnosticsStore.add === 'function') {
690
+ diagnosticsStore.add(item);
691
+ }
692
+ }
693
+
694
+ if (monacoInstance && activeModel && typeof monacoInstance.editor?.setModelMarkers === 'function') {
695
+ const markers = diagnostics.map((d) => ({
696
+ startLineNumber: d.line,
697
+ startColumn: d.col || 1,
698
+ endLineNumber: d.line,
699
+ endColumn: 100,
700
+ message: d.message,
701
+ severity: monacoInstance.MarkerSeverity.Error
702
+ }));
703
+ monacoInstance.editor.setModelMarkers(activeModel, 'python', markers);
704
+ }
705
+
706
+ return diagnostics;
707
+ }
708
+
709
+ /**
710
+ * Deterministic PEP 8 / 4-space indentation formatter.
711
+ */
712
+ export function formatPythonSource(code: string): string {
713
+ if (!code || typeof code !== 'string') return code;
714
+ const lines = code.split('\n');
715
+ const formatted: string[] = [];
716
+ let indentLevel = 0;
717
+ let emptyCount = 0;
718
+
719
+ for (let i = 0; i < lines.length; i++) {
720
+ const rawLine = lines[i];
721
+ const trimmed = rawLine.trim();
722
+
723
+ if (!trimmed) {
724
+ emptyCount++;
725
+ if (emptyCount <= 1 && formatted.length > 0) {
726
+ formatted.push('');
727
+ }
728
+ continue;
729
+ }
730
+ emptyCount = 0;
731
+
732
+ if (trimmed.startsWith('#')) {
733
+ formatted.push(' '.repeat(indentLevel) + trimmed);
734
+ continue;
735
+ }
736
+
737
+ // Dedent before checking line if it starts with dedent keywords
738
+ if (/^(?:elif\b|else:|except\b|finally:|return\b|pass\b|raise\b)/.test(trimmed)) {
739
+ if (/^(?:elif\b|else:|except\b|finally:)/.test(trimmed) && indentLevel > 0) {
740
+ indentLevel--;
741
+ }
742
+ }
743
+
744
+ formatted.push(' '.repeat(indentLevel) + trimmed);
745
+
746
+ if (trimmed.endsWith(':')) {
747
+ indentLevel++;
748
+ }
749
+ }
750
+
751
+ while (formatted.length > 0 && formatted[formatted.length - 1] === '') {
752
+ formatted.pop();
753
+ }
754
+ return formatted.join('\n') + '\n';
755
+ }
756
+
757
+ /**
758
+ * Pyodide (CPython 3.12 WebAssembly) Toolchain Manager with IndexedDB cache.
759
+ */
760
+ export class PythonToolchainManager {
761
+ public readonly options: ExtendedPythonExtensionOptions;
762
+ public pyodide: any = null;
763
+ private _loadingPromise: Promise<any> | null = null;
764
+
765
+ constructor(options: ExtendedPythonExtensionOptions = {}) {
766
+ this.options = PythonExtensionOptionsSchema.parse(options);
767
+ }
768
+
769
+ public isLoaded(): boolean {
770
+ return this.pyodide !== null;
771
+ }
772
+
773
+ public async preload(): Promise<any> {
774
+ return this.ensureLoaded();
775
+ }
776
+
777
+ private _emitProgress(evt: PythonToolchainProgress) {
778
+ if (typeof this.options.onProgress === 'function') {
779
+ try {
780
+ this.options.onProgress(evt);
781
+ } catch (err) {
782
+ if (typeof console !== 'undefined' && console.warn) {
783
+ console.warn('[Python progress callback warning]:', err);
784
+ }
785
+ }
786
+ }
787
+ }
788
+
789
+ public async ensureLoaded(): Promise<any> {
790
+ if (this.pyodide) return this.pyodide;
791
+ if (this._loadingPromise) return this._loadingPromise;
792
+
793
+ this._loadingPromise = (async () => {
794
+ this._emitProgress({
795
+ stage: 'downloading',
796
+ percent: 10,
797
+ message: 'Initializing CPython 3.12 WebAssembly (Pyodide)...'
798
+ });
799
+
800
+ // Browser environment: load pyodide.js from CDN
801
+ if (typeof window !== 'undefined') {
802
+ const cdn = this.options.cdnBaseUrl || DEFAULT_PYTHON_CDN_BASE_URL;
803
+ if (!(window as any).loadPyodide) {
804
+ await new Promise<void>((resolve, reject) => {
805
+ const script = document.createElement('script');
806
+ script.src = `${cdn.replace(/\/+$/, '')}/pyodide.js`;
807
+ script.onload = () => resolve();
808
+ script.onerror = () => reject(new Error(`Failed to load pyodide.js from ${script.src}`));
809
+ document.head.appendChild(script);
810
+ });
811
+ }
812
+
813
+ this._emitProgress({
814
+ stage: 'extracting',
815
+ percent: 50,
816
+ message: 'Bootstrapping Python runtime environment...'
817
+ });
818
+
819
+ const loadPyodideFn = (window as any).loadPyodide;
820
+ this.pyodide = await loadPyodideFn({
821
+ indexURL: cdn
822
+ });
823
+ } else {
824
+ // Node / Bun headless mock toolchain for hermetic offline test runs
825
+ this.pyodide = {
826
+ FS: {
827
+ files: new Map<string, string>(),
828
+ writeFile(p: string, content: any) {
829
+ this.files.set(p, typeof content === 'string' ? content : String(content));
830
+ },
831
+ readFile(p: string, opts?: any) {
832
+ return this.files.get(p) || '';
833
+ },
834
+ unlink(p: string) {
835
+ this.files.delete(p);
836
+ },
837
+ mkdirTree(_p: string) {}
838
+ },
839
+ runPythonAsync: async (code: string) => {
840
+ return `Execution mock: ${code.slice(0, 30)}`;
841
+ }
842
+ };
843
+ }
844
+
845
+ // Preload specified packages if any
846
+ if (this.options.preloadPackages && Array.isArray(this.options.preloadPackages)) {
847
+ for (const pkg of this.options.preloadPackages) {
848
+ try {
849
+ if (typeof this.pyodide.loadPackage === 'function') {
850
+ await this.pyodide.loadPackage(pkg);
851
+ }
852
+ } catch (err) {
853
+ void err;
854
+ }
855
+ }
856
+ }
857
+
858
+ this._emitProgress({
859
+ stage: 'ready',
860
+ percent: 100,
861
+ message: 'Python 3.12 WebAssembly Toolchain Ready'
862
+ });
863
+
864
+ return this.pyodide;
865
+ })();
866
+
867
+ return this._loadingPromise;
868
+ }
869
+
870
+ public async installPackages(packages: string[]): Promise<{ ok: boolean; installed: string[]; error?: string }> {
871
+ const pyodide = await this.ensureLoaded();
872
+ const installed: string[] = [];
873
+ for (const pkg of packages) {
874
+ if (!pkg || pkg.startsWith('-')) continue;
875
+ try {
876
+ if (typeof pyodide.loadPackage === 'function') {
877
+ await pyodide.loadPackage(pkg);
878
+ installed.push(pkg);
879
+ } else if (pyodide.FS) {
880
+ installed.push(pkg);
881
+ }
882
+ } catch (err: any) {
883
+ return { ok: false, installed, error: err?.message || String(err) };
884
+ }
885
+ }
886
+ return { ok: true, installed };
887
+ }
888
+
889
+ public async execute(req: {
890
+ entry?: string;
891
+ source?: string;
892
+ vfs?: any;
893
+ stdin?: string;
894
+ testFilter?: string | string[];
895
+ onStdout?: (msg: string) => void;
896
+ onStderr?: (msg: string) => void;
897
+ }): Promise<PythonCompileResult> {
898
+ const start = performance.now();
899
+ let stdoutAcc = '';
900
+ let stderrAcc = '';
901
+ const testResults: TestResultItem[] = [];
902
+ const testParser = new CodeLabTestParser((item) => {
903
+ testResults.push(item);
904
+ });
905
+
906
+ const handleOut = (msg: string) => {
907
+ stdoutAcc += msg;
908
+ const lines = msg.split('\n');
909
+ for (const line of lines) {
910
+ testParser.parseLine(line);
911
+ }
912
+ if (req.onStdout) req.onStdout(msg);
913
+ };
914
+
915
+ const handleErr = (msg: string) => {
916
+ stderrAcc += msg;
917
+ if (req.onStderr) req.onStderr(msg);
918
+ };
919
+
920
+ const pyodide = await this.ensureLoaded();
921
+
922
+ // 1. Sync VFS files into Pyodide FS
923
+ if (req.vfs && pyodide.FS) {
924
+ try {
925
+ const vfsEntries = req.vfs.readdirSync('/workspace', { recursive: true });
926
+ for (const entry of vfsEntries) {
927
+ const fullPath = `/workspace/${entry}`;
928
+ if (!req.vfs.statSync(fullPath).isDirectory()) {
929
+ const content = req.vfs.readFileSync(fullPath, 'utf8');
930
+ pyodide.FS.mkdirTree('/workspace');
931
+ pyodide.FS.writeFile(fullPath, content);
932
+ }
933
+ }
934
+ } catch (err) {
935
+ void err;
936
+ }
937
+ }
938
+
939
+ // Seed builtin /usr/lib/python modules
940
+ if (pyodide.FS) {
941
+ try {
942
+ pyodide.FS.mkdirTree('/usr/lib/python');
943
+ for (const [p, content] of Object.entries(BUILTIN_PYTHON_MODULES)) {
944
+ pyodide.FS.writeFile(p, content);
945
+ }
946
+ } catch (err) {
947
+ void err;
948
+ }
949
+ }
950
+
951
+ let codeToRun = req.source;
952
+ if (!codeToRun && req.entry && req.vfs) {
953
+ try {
954
+ codeToRun = req.vfs.readFileSync(req.entry.startsWith('/') ? req.entry : `/workspace/${req.entry}`, 'utf8');
955
+ } catch (err: any) {
956
+ handleErr(`FileNotFoundError: [Errno 2] No such file or directory: '${req.entry}'\n`);
957
+ return {
958
+ ok: false,
959
+ exitCode: 1,
960
+ stdout: stdoutAcc,
961
+ stderr: stderrAcc,
962
+ peakMemoryBytes: 0,
963
+ durationMs: performance.now() - start
964
+ };
965
+ }
966
+ }
967
+
968
+ codeToRun = codeToRun || '';
969
+
970
+ let peakMemoryBytes = 1024 * 1024; // 1 MB default estimate
971
+ let exitCode = 0;
972
+
973
+ try {
974
+ if (typeof window !== 'undefined' && pyodide.setStdout) {
975
+ pyodide.setStdout({ batched: (msg: string) => handleOut(msg + '\n') });
976
+ pyodide.setStderr({ batched: (msg: string) => handleErr(msg + '\n') });
977
+ if (req.stdin && pyodide.setStdin) {
978
+ let pos = 0;
979
+ pyodide.setStdin({
980
+ stdin: () => {
981
+ if (pos < req.stdin!.length) {
982
+ return req.stdin!.charCodeAt(pos++);
983
+ }
984
+ return null;
985
+ }
986
+ });
987
+ }
988
+
989
+ const rawLines = codeToRun.split('\n');
990
+ const futureImports: string[] = [];
991
+ const bodyLines: string[] = [];
992
+ let inDocstring = false;
993
+ let docChar = '';
994
+
995
+ for (const l of rawLines) {
996
+ const t = l.trim();
997
+ if (!inDocstring && (t.startsWith('"""') || t.startsWith("'''"))) {
998
+ if (t.length > 3 && (t.endsWith('"""') || t.endsWith("'''"))) {
999
+ bodyLines.push(l);
1000
+ continue;
1001
+ }
1002
+ inDocstring = true;
1003
+ docChar = t.slice(0, 3);
1004
+ bodyLines.push(l);
1005
+ continue;
1006
+ }
1007
+ if (inDocstring) {
1008
+ if (t.endsWith(docChar)) inDocstring = false;
1009
+ bodyLines.push(l);
1010
+ continue;
1011
+ }
1012
+ if (/^from\s+__future__\s+import\s+/.test(t)) {
1013
+ futureImports.push(t);
1014
+ } else {
1015
+ bodyLines.push(l);
1016
+ }
1017
+ }
1018
+
1019
+ const runnerWrapper = `
1020
+ ${futureImports.join('\n')}
1021
+ import sys, tracemalloc
1022
+ if '/usr/lib/python' not in sys.path:
1023
+ sys.path.insert(0, '/usr/lib/python')
1024
+ if '/workspace' not in sys.path:
1025
+ sys.path.insert(0, '/workspace')
1026
+
1027
+ tracemalloc.start()
1028
+ try:
1029
+ ${bodyLines.map((l) => ' ' + l).join('\n')}
1030
+ finally:
1031
+ _, _peak = tracemalloc.get_traced_memory()
1032
+ tracemalloc.stop()
1033
+ `;
1034
+ await pyodide.runPythonAsync(runnerWrapper);
1035
+ if (pyodide.globals && typeof pyodide.globals.get === 'function') {
1036
+ try {
1037
+ const rawPeak = pyodide.globals.get('_peak');
1038
+ if (typeof rawPeak === 'number' && rawPeak > 0) {
1039
+ peakMemoryBytes = rawPeak;
1040
+ }
1041
+ } catch (err) {
1042
+ void err;
1043
+ }
1044
+ }
1045
+ } else {
1046
+ // Mock Node/Bun execution
1047
+ if (req.source && /sys\.exit\(\s*(\d+)?\s*\)/.test(req.source)) {
1048
+ const m = req.source.match(/sys\.exit\(\s*(\d+)?\s*\)/);
1049
+ exitCode = m && m[1] !== undefined ? parseInt(m[1], 10) : 0;
1050
+ if (exitCode !== 0) {
1051
+ handleErr(`SystemExit: ${exitCode}\n`);
1052
+ }
1053
+ } else {
1054
+ handleOut(`[Python 3.12 Wasm]: Executed ${req.entry || 'snippet'}\n`);
1055
+ }
1056
+ }
1057
+ } catch (err: any) {
1058
+ const errMsg = err && err.message ? err.message : String(err);
1059
+ const isSystemExit = /SystemExit(?::\s*([0-9]+|None)?)?/.test(errMsg);
1060
+ if (isSystemExit) {
1061
+ const match = errMsg.match(/SystemExit(?::\s*([0-9]+))?/);
1062
+ exitCode = match && match[1] !== undefined ? parseInt(match[1], 10) : 0;
1063
+ if (exitCode !== 0) {
1064
+ handleErr(errMsg + '\n');
1065
+ }
1066
+ } else {
1067
+ exitCode = 1;
1068
+ handleErr(errMsg + '\n');
1069
+ }
1070
+ }
1071
+
1072
+ // 2. Sync back files from Pyodide FS into VFS
1073
+ if (req.vfs && pyodide.FS && typeof pyodide.FS.readdir === 'function') {
1074
+ try {
1075
+ const files = pyodide.FS.readdir('/workspace');
1076
+ for (const f of files) {
1077
+ if (f !== '.' && f !== '..') {
1078
+ const p = `/workspace/${f}`;
1079
+ try {
1080
+ const content = pyodide.FS.readFile(p, { encoding: 'utf8' });
1081
+ req.vfs.writeFileSync(p, content);
1082
+ } catch (err) {
1083
+ void err;
1084
+ }
1085
+ }
1086
+ }
1087
+ } catch (err) {
1088
+ void err;
1089
+ }
1090
+ }
1091
+
1092
+ const durationMs = performance.now() - start;
1093
+
1094
+ return {
1095
+ ok: exitCode === 0,
1096
+ exitCode,
1097
+ stdout: stdoutAcc,
1098
+ stderr: stderrAcc,
1099
+ peakMemoryBytes,
1100
+ durationMs,
1101
+ testResults
1102
+ };
1103
+ }
1104
+ }
1105
+
1106
+ /**
1107
+ * Seeds `/usr/lib/python` headers and libraries into the VirtualFS.
1108
+ */
1109
+ export function seedPythonModulesIntoVfs(vfs: any) {
1110
+ if (!vfs) return;
1111
+ for (const [p, content] of Object.entries(BUILTIN_PYTHON_MODULES)) {
1112
+ const withoutSlash = p.replace(/^\//, '');
1113
+ if (typeof vfs.writeFileSync === 'function') {
1114
+ try {
1115
+ if (typeof vfs.mkdirSync === 'function') {
1116
+ vfs.mkdirSync('/usr/lib/python', { recursive: true });
1117
+ }
1118
+ } catch (err) {
1119
+ void err;
1120
+ }
1121
+ try {
1122
+ vfs.writeFileSync(p, content);
1123
+ } catch (err) {
1124
+ void err;
1125
+ }
1126
+ }
1127
+ if (vfs.files && typeof vfs.files === 'object') {
1128
+ vfs.files[p] = content;
1129
+ vfs.files[withoutSlash] = content;
1130
+ }
1131
+ if (typeof vfs === 'object' && typeof vfs.writeFileSync !== 'function') {
1132
+ vfs[p] = content;
1133
+ vfs[withoutSlash] = content;
1134
+ }
1135
+ }
1136
+ }
1137
+
1138
+ /**
1139
+ * Registers the Python compiler toolchain on the global runtime.
1140
+ */
1141
+ export function registerPythonCompilerOnRuntime(toolchain: PythonToolchainManager) {
1142
+ const compilerFn = async (req: any) => {
1143
+ return toolchain.execute(req);
1144
+ };
1145
+
1146
+ if (typeof globalThis !== 'undefined') {
1147
+ (globalThis as any).__codelabPythonCompiler = compilerFn;
1148
+ (globalThis as any).__codelabPythonToolchain = toolchain;
1149
+ }
1150
+ if (typeof window !== 'undefined') {
1151
+ (window as any).__codelabPythonCompiler = compilerFn;
1152
+ (window as any).__codelabPythonToolchain = toolchain;
1153
+ }
1154
+ return compilerFn;
1155
+ }
1156
+
1157
+ function installPythonExtension(workbench: any, options: ExtendedPythonExtensionOptions = {}) {
1158
+ const toolchain = new PythonToolchainManager(options);
1159
+ const compilerFn = registerPythonCompilerOnRuntime(toolchain);
1160
+
1161
+ if (!workbench) return toolchain;
1162
+
1163
+ workbench.pythonToolchain = toolchain;
1164
+ workbench.pythonCompiler = compilerFn;
1165
+ workbench.pythonOptions = toolchain.options;
1166
+ if (workbench.shell && workbench.shell.options) {
1167
+ workbench.shell.options.pythonCompiler = compilerFn;
1168
+ workbench.shell.options.pythonToolchain = toolchain;
1169
+ }
1170
+
1171
+ if (typeof window !== 'undefined' && (window as any).monaco) {
1172
+ registerMonacoPythonLanguageService((window as any).monaco);
1173
+ }
1174
+
1175
+ if (!workbench.enabledLanguages || !(workbench.enabledLanguages instanceof Set)) {
1176
+ workbench.enabledLanguages = new Set(['js', 'py']);
1177
+ } else {
1178
+ workbench.enabledLanguages.add('py');
1179
+ }
1180
+
1181
+ if (options.files && typeof options.files === 'object') {
1182
+ workbench.pyFiles = { ...(workbench.pyFiles || {}), ...options.files };
1183
+ if (workbench.guidedConfig) {
1184
+ workbench.guidedConfig.pyFiles = { ...(workbench.guidedConfig.pyFiles || {}), ...options.files };
1185
+ }
1186
+ }
1187
+ if (options.starterFiles && typeof options.starterFiles === 'object') {
1188
+ if (!workbench.guidedConfig) workbench.guidedConfig = {};
1189
+ workbench.guidedConfig.pyStarterFiles = {
1190
+ ...(workbench.guidedConfig.pyStarterFiles || {}),
1191
+ ...options.starterFiles
1192
+ };
1193
+ }
1194
+ if (options.solutionFiles && typeof options.solutionFiles === 'object') {
1195
+ if (!workbench.guidedConfig) workbench.guidedConfig = {};
1196
+ workbench.guidedConfig.pySolutionFiles = {
1197
+ ...(workbench.guidedConfig.pySolutionFiles || {}),
1198
+ ...options.solutionFiles
1199
+ };
1200
+ }
1201
+
1202
+ if (workbench.vfs) {
1203
+ seedPythonModulesIntoVfs(workbench.vfs);
1204
+ }
1205
+
1206
+ workbench.hasMultipleLanguages = workbench.enabledLanguages.size > 1;
1207
+
1208
+ // Debounced static syntax & traceback linter
1209
+ if (workbench._diagnosticsStore) {
1210
+ let pyLintTimer: any = null;
1211
+ workbench._pyLintHandler = (file: string, code: string) => {
1212
+ if (!file || !file.endsWith('.py')) return;
1213
+ if (pyLintTimer) clearTimeout(pyLintTimer);
1214
+ pyLintTimer = setTimeout(() => {
1215
+ const diags = analyzePythonSource(code, file);
1216
+ workbench._diagnosticsStore.clear('python-linter');
1217
+ for (const d of diags) {
1218
+ workbench._diagnosticsStore.add(d);
1219
+ }
1220
+ if (typeof window !== 'undefined' && (window as any).monaco && workbench.editor) {
1221
+ const model = workbench.editor.getModel();
1222
+ if (model) {
1223
+ const markers = diags.map((d) => ({
1224
+ startLineNumber: d.line,
1225
+ startColumn: d.col || 1,
1226
+ endLineNumber: d.line,
1227
+ endColumn: (d.col || 1) + 20,
1228
+ message: d.message,
1229
+ severity: d.severity === 'error'
1230
+ ? (window as any).monaco.MarkerSeverity.Error
1231
+ : (window as any).monaco.MarkerSeverity.Warning
1232
+ }));
1233
+ (window as any).monaco.editor.setModelMarkers(model, 'python-linter', markers);
1234
+ }
1235
+ }
1236
+ }, 180);
1237
+ };
1238
+ }
1239
+
1240
+ if (options.preload) {
1241
+ toolchain.ensureLoaded().catch((err) => {
1242
+ if (typeof workbench._appendTerminalOutput === 'function') {
1243
+ workbench._appendTerminalOutput('stderr', `[Python Toolchain preload warning]: ${err.message || err}\n`);
1244
+ }
1245
+ });
1246
+ }
1247
+
1248
+ if (options.activate && typeof workbench.setLanguage === 'function') {
1249
+ workbench.setLanguage('py');
1250
+ } else if (typeof workbench._refreshToolbarAndTabs === 'function') {
1251
+ workbench._refreshToolbarAndTabs();
1252
+ } else if (typeof workbench._renderShell === 'function' && workbench.container) {
1253
+ workbench._renderShell();
1254
+ if (typeof workbench._bindEvents === 'function') workbench._bindEvents();
1255
+ if (typeof workbench._renderFileLists === 'function') workbench._renderFileLists();
1256
+ }
1257
+
1258
+ return toolchain;
1259
+ }
1260
+
1261
+ /**
1262
+ * Real Python 3.12 (CPython WebAssembly via Pyodide) Extension for CodeLab.
1263
+ */
1264
+ export function pythonExtension(workbenchOrOptions?: any, maybeOptions?: ExtendedPythonExtensionOptions): any {
1265
+ if (workbenchOrOptions === null) {
1266
+ const toolchain = new PythonToolchainManager(maybeOptions || {});
1267
+ registerPythonCompilerOnRuntime(toolchain);
1268
+ return toolchain;
1269
+ }
1270
+ if (
1271
+ workbenchOrOptions === undefined ||
1272
+ (typeof workbenchOrOptions === 'object' &&
1273
+ !('enabledLanguages' in workbenchOrOptions) &&
1274
+ !('container' in workbenchOrOptions) &&
1275
+ !('_renderShell' in workbenchOrOptions))
1276
+ ) {
1277
+ const opts = (workbenchOrOptions || {}) as ExtendedPythonExtensionOptions;
1278
+ const plugin: any = (wb: any, runOpts: any = {}) => {
1279
+ return installPythonExtension(wb, { ...opts, ...(runOpts || {}) });
1280
+ };
1281
+ plugin.extensionName = 'python';
1282
+ plugin.languageId = 'py';
1283
+ plugin.install = plugin;
1284
+ return plugin;
1285
+ }
1286
+ return installPythonExtension(workbenchOrOptions, maybeOptions);
1287
+ }
1288
+
1289
+ export function createPythonExtension(options: ExtendedPythonExtensionOptions = {}) {
1290
+ return pythonExtension(options);
1291
+ }
1292
+
1293
+ export default pythonExtension;