forked from jupyterlite/javascript-kernel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecutor.ts
More file actions
1934 lines (1726 loc) · 54.9 KB
/
executor.ts
File metadata and controls
1934 lines (1726 loc) · 54.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import type { KernelMessage } from '@jupyterlab/services';
import { parseScript } from 'meriyah';
import { generate } from 'astring';
import type { IMimeBundle } from '@jupyterlab/nbformat';
export { IDisplayData, IDisplayCallbacks, DisplayHelper } from './display';
/**
* Configuration for magic imports.
*/
export interface IMagicImportsConfig {
enabled: boolean;
baseUrl: string;
enableAutoNpm: boolean;
}
/**
* Result of making code async.
*/
export interface IAsyncCodeResult {
asyncFunction: () => Promise<any>;
withReturn: boolean;
}
/**
* Information about an extracted import.
*/
export interface IImportInfo {
/** The original import source (e.g., 'canvas-confetti') */
source: string;
/** The transformed URL (e.g., 'https://cdn.jsdelivr.net/npm/canvas-confetti/+esm') */
url: string;
/** The local variable name for default import */
defaultImport?: string;
/** The local variable name for namespace import */
namespaceImport?: string;
/** Named imports: { importedName: localName } */
namedImports: Record<string, string>;
}
type JSCallable = (...args: any[]) => any;
/**
* Result of code completion.
*/
export interface ICompletionResult {
matches: string[];
cursorStart: number;
cursorEnd?: number;
status?: string;
}
/**
* Result of code completeness check.
*/
export type IIsCompleteResult =
| KernelMessage.IIsCompleteReplyIncomplete
| KernelMessage.IIsCompleteReplyOther;
/**
* Result of code inspection.
*/
export type IInspectResult = KernelMessage.IInspectReply;
/**
* Registry for tracking code declarations across cells.
* Allows deduplication - later definitions override earlier ones.
*/
export interface ICodeRegistry {
/** Function declarations by name (setup, draw, etc.) */
functions: Map<string, any>;
/** Variable declarations by name */
variables: Map<string, any>;
/** Class declarations by name */
classes: Map<string, any>;
/** Other top-level statements (expressions, etc.) in execution order */
statements: any[];
}
/**
* Configuration for the JavaScript executor.
*/
export class ExecutorConfig {
/**
* Get the magic imports configuration.
*/
get magicImports(): IMagicImportsConfig {
return this._magicImports;
}
/**
* Set the magic imports configuration.
*/
set magicImports(value: IMagicImportsConfig) {
this._magicImports = value;
}
private _magicImports: IMagicImportsConfig = {
enabled: true,
baseUrl: 'https://cdn.jsdelivr.net/',
enableAutoNpm: true
};
}
/**
* JavaScript code executor with advanced features.
*/
export class JavaScriptExecutor {
/**
* Instantiate a new JavaScriptExecutor.
*
* @param globalScope - The global scope (globalThis) for code execution.
* @param config - Optional executor configuration.
*/
constructor(globalScope: Record<string, any>, config?: ExecutorConfig) {
this._globalScope = globalScope;
this._config = config || new ExecutorConfig();
}
/**
* Convert user code to an async function.
*
* @param code - The user code to convert.
* @returns The async function and whether it has a return value.
*/
makeAsyncFromCode(code: string): IAsyncCodeResult {
if (code.length === 0) {
return {
asyncFunction: async () => {},
withReturn: false
};
}
const ast = parseScript(code, {
ranges: true,
module: true
});
// Add top-level variables to global scope
let codeAddToGlobalScope = this._addToGlobalScope(ast);
// Handle last statement / add return if needed
const { withReturn, modifiedUserCode, extraReturnCode } =
this._handleLastStatement(code, ast);
let finalCode = modifiedUserCode;
// Handle import statements
const importResult = this._rewriteImportStatements(finalCode, ast);
finalCode = importResult.modifiedUserCode;
codeAddToGlobalScope += importResult.codeAddToGlobalScope;
const combinedCode = `
${finalCode}
${codeAddToGlobalScope}
${extraReturnCode}
`;
const asyncFunctionFactory = this._createScopedFunction(`
return async function() {
${combinedCode}
};
`) as () => () => Promise<any>;
const asyncFunction = asyncFunctionFactory.call(this._globalScope);
return {
asyncFunction,
withReturn
};
}
/**
* Extract import information from code without executing it.
* Used to track imports for sketch generation.
*
* @param code - The code to analyze for imports.
* @returns Array of import information objects.
*/
extractImports(code: string): IImportInfo[] {
if (code.length === 0) {
return [];
}
try {
const ast = parseScript(code, {
ranges: true,
module: true
});
const imports: IImportInfo[] = [];
for (const node of ast.body) {
if (node.type === 'ImportDeclaration') {
const source = String(node.source.value);
const url = this._transformImportSource(source);
const importInfo: IImportInfo = {
source,
url,
namedImports: {}
};
for (const specifier of node.specifiers) {
if (specifier.type === 'ImportDefaultSpecifier') {
importInfo.defaultImport = specifier.local.name;
} else if (specifier.type === 'ImportNamespaceSpecifier') {
importInfo.namespaceImport = specifier.local.name;
} else if (specifier.type === 'ImportSpecifier') {
if (specifier.imported.name === 'default') {
importInfo.defaultImport = specifier.local.name;
} else {
importInfo.namedImports[specifier.imported.name] =
specifier.local.name;
}
}
}
imports.push(importInfo);
}
}
return imports;
} catch {
return [];
}
}
/**
* Generate async JavaScript code to load imports and assign them to globalThis.
* This is used when generating the sketch iframe.
*
* @param imports - The import information objects.
* @returns Generated JavaScript code string.
*/
generateImportCode(imports: IImportInfo[]): string {
if (imports.length === 0) {
return '';
}
const lines: string[] = [];
for (const imp of imports) {
const importCall = `import(${JSON.stringify(imp.url)})`;
if (imp.defaultImport) {
lines.push(
`const { default: ${imp.defaultImport} } = await ${importCall};`
);
lines.push(
`globalThis["${imp.defaultImport}"] = ${imp.defaultImport};`
);
}
if (imp.namespaceImport) {
lines.push(`const ${imp.namespaceImport} = await ${importCall};`);
lines.push(
`globalThis["${imp.namespaceImport}"] = ${imp.namespaceImport};`
);
}
const namedKeys = Object.keys(imp.namedImports);
if (namedKeys.length > 0) {
const destructure = namedKeys
.map(k =>
k === imp.namedImports[k] ? k : `${k}: ${imp.namedImports[k]}`
)
.join(', ');
lines.push(`const { ${destructure} } = await ${importCall};`);
for (const importedName of namedKeys) {
const localName = imp.namedImports[importedName];
lines.push(`globalThis["${localName}"] = ${localName};`);
}
}
// Side-effect only import (no specifiers)
if (
!imp.defaultImport &&
!imp.namespaceImport &&
Object.keys(imp.namedImports).length === 0
) {
lines.push(`await ${importCall};`);
}
}
return lines.join('\n');
}
/**
* Create a new empty code registry.
*/
createCodeRegistry(): ICodeRegistry {
return {
functions: new Map(),
variables: new Map(),
classes: new Map(),
statements: []
};
}
/**
* Register code from executed cells into the registry.
* Later definitions of the same name will override earlier ones.
* Import declarations are skipped (handled separately).
*
* @param code - The code to register.
* @param registry - The registry to add declarations to.
*/
registerCode(code: string, registry: ICodeRegistry): void {
if (code.trim().length === 0) {
return;
}
try {
const ast = parseScript(code, {
ranges: true,
module: true
});
for (const node of ast.body) {
switch (node.type) {
case 'FunctionDeclaration':
// Store function by name - later definitions override
if (node.id && node.id.name) {
registry.functions.set(node.id.name, node);
}
break;
case 'ClassDeclaration':
// Store class by name - later definitions override
if (node.id && node.id.name) {
registry.classes.set(node.id.name, node);
}
break;
case 'VariableDeclaration':
// For variable declarations, extract each declarator
for (const declarator of node.declarations) {
if (declarator.id.type === 'Identifier') {
// Store the whole declaration node with just this declarator
const singleDecl = {
...node,
declarations: [declarator]
};
registry.variables.set(declarator.id.name, singleDecl);
} else if (declarator.id.type === 'ObjectPattern') {
// Handle destructuring: const { a, b } = obj
for (const prop of declarator.id.properties) {
if (
prop.type === 'Property' &&
prop.key.type === 'Identifier'
) {
const name =
prop.value?.type === 'Identifier'
? prop.value.name
: prop.key.name;
registry.variables.set(name, {
...node,
declarations: [declarator],
_destructuredName: name
});
}
}
} else if (declarator.id.type === 'ArrayPattern') {
// Handle array destructuring: const [a, b] = arr
for (const element of declarator.id.elements) {
if (element && element.type === 'Identifier') {
registry.variables.set(element.name, {
...node,
declarations: [declarator],
_destructuredName: element.name
});
}
}
}
}
break;
case 'ImportDeclaration':
// Skip imports - handled separately via extractImports
break;
case 'ExpressionStatement':
registry.statements.push(node);
break;
default:
// Other statements (if, for, while, etc.) - keep in order
registry.statements.push(node);
break;
}
}
} catch {
// If parsing fails, we can't register the code
}
}
/**
* Generate code from the registry.
* Produces clean, deduplicated code for regeneration scenarios.
* Includes globalThis assignments so declarations are accessible globally.
*
* @param registry - The registry to generate code from.
* @returns Generated JavaScript code string.
*/
generateCodeFromRegistry(registry: ICodeRegistry): string {
const programBody: any[] = [];
const globalAssignments: string[] = [];
// Add variables first (they might be used by functions)
const seenDestructuringDecls = new Set<string>();
for (const [name, node] of registry.variables) {
// For destructuring, only add once per actual declaration
if (node._destructuredName) {
const declKey = generate(node.declarations[0]);
if (seenDestructuringDecls.has(declKey)) {
continue;
}
seenDestructuringDecls.add(declKey);
// Remove the marker before generating
const cleanNode = { ...node };
delete cleanNode._destructuredName;
programBody.push(cleanNode);
} else {
programBody.push(node);
}
globalAssignments.push(`globalThis["${name}"] = ${name};`);
}
// Add classes
for (const [name, node] of registry.classes) {
programBody.push(node);
globalAssignments.push(`globalThis["${name}"] = ${name};`);
}
// Add functions
for (const [name, node] of registry.functions) {
programBody.push(node);
globalAssignments.push(`globalThis["${name}"] = ${name};`);
}
// Add other statements in order
for (const node of registry.statements) {
programBody.push(node);
}
// Create a program AST and generate code
const program = {
type: 'Program',
body: programBody,
sourceType: 'script'
};
// Generate the code and append globalThis assignments
const generatedCode = generate(program);
if (globalAssignments.length > 0) {
return generatedCode + '\n' + globalAssignments.join('\n');
}
return generatedCode;
}
/**
* Get MIME bundle for a value.
* Supports custom output methods:
* - _toHtml() for text/html
* - _toSvg() for image/svg+xml
* - _toPng() for image/png (base64)
* - _toJpeg() for image/jpeg (base64)
* - _toMime() for custom MIME bundle
* - inspect() for text/plain (Node.js style)
*
* @param value - The value to convert to a MIME bundle.
* @returns The MIME bundle representation of the value.
*/
getMimeBundle(value: any): IMimeBundle {
// Handle null and undefined
if (value === null) {
return { 'text/plain': 'null' };
}
if (value === undefined) {
return { 'text/plain': 'undefined' };
}
// Check for custom MIME output methods
if (typeof value === 'object' && value !== null) {
const customMime = this._getCustomMimeBundle(value);
if (customMime) {
return customMime;
}
}
// Handle primitives
if (typeof value === 'string') {
// Check if it looks like HTML (must start with a valid tag: <div>, <p class="...">,
// <!DOCTYPE>, <!-- -->, <br/>, etc.). Rejects non-HTML like "<a, b>".
const trimmed = value.trim();
if (
/^<(?:[a-zA-Z][a-zA-Z0-9-]*[\s/>]|!(?:DOCTYPE|--))/.test(trimmed) &&
trimmed.endsWith('>')
) {
return {
'text/html': value,
'text/plain': value
};
}
return { 'text/plain': `'${value}'` };
}
if (typeof value === 'number' || typeof value === 'boolean') {
return { 'text/plain': String(value) };
}
// Handle Symbol
if (typeof value === 'symbol') {
return { 'text/plain': value.toString() };
}
// Handle BigInt
if (typeof value === 'bigint') {
return { 'text/plain': `${value.toString()}n` };
}
// Handle functions
if (typeof value === 'function') {
const funcString = value.toString();
const name = value.name || 'anonymous';
return {
'text/plain': `[Function: ${name}]`,
'text/html': `<pre style="margin:0"><code>${this._escapeHtml(funcString)}</code></pre>`
};
}
// Handle Error objects
if (this._isInstanceOfRealm(value, 'Error')) {
const errorValue = value as Error;
return {
'text/plain': errorValue.stack || errorValue.toString(),
'application/json': {
name: errorValue.name,
message: errorValue.message,
stack: errorValue.stack
}
};
}
// Handle Date objects
if (this._isInstanceOfRealm(value, 'Date')) {
const dateValue = value as Date;
return {
'text/plain': dateValue.toISOString(),
'application/json': dateValue.toISOString()
};
}
// Handle RegExp objects
if (this._isInstanceOfRealm(value, 'RegExp')) {
return { 'text/plain': (value as RegExp).toString() };
}
// Handle Map
if (this._isInstanceOfRealm(value, 'Map')) {
const mapValue = value as Map<any, any>;
const entries = Array.from(mapValue.entries());
try {
return {
'text/plain': `Map(${mapValue.size}) { ${entries.map(([k, v]) => `${String(k)} => ${String(v)}`).join(', ')} }`,
'application/json': Object.fromEntries(entries)
};
} catch {
return { 'text/plain': `Map(${mapValue.size})` };
}
}
// Handle Set
if (this._isInstanceOfRealm(value, 'Set')) {
const setValue = value as Set<any>;
const items = Array.from(setValue);
try {
return {
'text/plain': `Set(${setValue.size}) { ${items.map(v => String(v)).join(', ')} }`,
'application/json': items
};
} catch {
return { 'text/plain': `Set(${setValue.size})` };
}
}
// Handle DOM elements (Canvas, HTMLElement, etc.)
if (this._isDOMElement(value)) {
return this._getDOMElementMimeBundle(value);
}
// Handle arrays
if (Array.isArray(value)) {
try {
const preview = this._formatArrayPreview(value);
return {
'application/json': value,
'text/plain': preview
};
} catch {
return { 'text/plain': `Array(${value.length})` };
}
}
// Handle typed arrays
if (ArrayBuffer.isView(value)) {
const typedArray = value as unknown as { length: number };
return {
'text/plain': `${value.constructor.name}(${typedArray.length})`
};
}
// Handle Promise (show as pending)
if (this._isInstanceOfRealm(value, 'Promise')) {
return { 'text/plain': 'Promise { <pending> }' };
}
// Handle generic objects
if (typeof value === 'object') {
// Check if it's already a mime bundle (has data with MIME-type keys)
if (value.data && typeof value.data === 'object') {
const dataKeys = Object.keys(value.data);
const hasMimeKeys = dataKeys.some(key => key.includes('/'));
if (hasMimeKeys) {
return value.data;
}
}
try {
const preview = this._formatObjectPreview(value);
return {
'application/json': value,
'text/plain': preview
};
} catch {
// Object might have circular references or be non-serializable
return { 'text/plain': this._formatNonSerializableObject(value) };
}
}
// Fallback
return { 'text/plain': String(value) };
}
/**
* Complete code at cursor position.
*
* @param codeLine - The line of code to complete.
* @param globalScope - The global scope for variable lookup.
* @returns The completion result with matches and cursor position.
*/
completeLine(
codeLine: string,
globalScope: any = this._globalScope
): ICompletionResult {
// Remove unwanted left part
const stopChars = ' {}()=+-*/%&|^~<>,:;!?@#';
let codeBegin = 0;
for (let i = codeLine.length - 1; i >= 0; i--) {
if (stopChars.includes(codeLine[i])) {
codeBegin = i + 1;
break;
}
}
const pseudoExpression = codeLine.substring(codeBegin);
// Find part right of dot/bracket
const expStopChars = '.]';
let splitPos = pseudoExpression.length;
let found = false;
for (let i = splitPos - 1; i >= 0; i--) {
if (expStopChars.includes(pseudoExpression[i])) {
splitPos = i;
found = true;
break;
}
}
let rootObjectStr = '';
let toMatch = pseudoExpression;
let cursorStart = codeBegin;
if (found) {
rootObjectStr = pseudoExpression.substring(0, splitPos);
toMatch = pseudoExpression.substring(splitPos + 1);
cursorStart += splitPos + 1;
}
// Find root object
let rootObject = globalScope;
if (rootObjectStr !== '') {
try {
const evalFunc = this._createScopedFunction(
'scope',
`with(scope) { return ${rootObjectStr}; }`
) as (scope: any) => any;
rootObject = evalFunc(globalScope);
} catch {
return {
matches: [],
cursorStart,
status: 'error'
};
}
}
// Collect all properties including from prototype chain
const matches = this._getAllProperties(rootObject, toMatch);
return {
matches,
cursorStart
};
}
/**
* Complete request with multi-line support.
*
* @param code - The full code content.
* @param cursorPos - The cursor position in the code.
* @returns The completion result with matches and cursor positions.
*/
completeRequest(code: string, cursorPos: number): ICompletionResult {
const lines = code.split('\n');
// Find line the cursor is on
let lineIndex = 0;
let cursorPosInLine = 0;
let lineBegin = 0;
for (let i = 0; i < lines.length; i++) {
if (cursorPos >= lineBegin && cursorPos <= lineBegin + lines[i].length) {
lineIndex = i;
cursorPosInLine = cursorPos - lineBegin;
break;
}
lineBegin += lines[i].length + 1; // +1 for \n
}
const codeLine = lines[lineIndex];
const codePrefix = codeLine.slice(0, cursorPosInLine);
const lineRes = this.completeLine(codePrefix);
const matches = lineRes.matches;
const inLineCursorStart = lineRes.cursorStart;
const tail = codeLine.slice(cursorPosInLine);
const cursorTail = tail.match(/^[\w$]*/)?.[0] ?? '';
return {
matches,
cursorStart: lineBegin + inLineCursorStart,
cursorEnd: cursorPos + cursorTail.length,
status: lineRes.status || 'ok'
};
}
/**
* Clean stack trace to remove internal frames.
*
* @param error - The error with stack trace to clean.
* @returns The cleaned stack trace string.
*/
cleanStackTrace(error: Error): string {
const errStackStr = error.stack || '';
const errStackLines = errStackStr.split('\n');
const usedLines: string[] = [];
for (const line of errStackLines) {
// Stop at internal implementation details
if (
line.includes('makeAsyncFromCode') ||
line.includes('new Function') ||
line.includes('asyncFunction')
) {
break;
}
usedLines.push(line);
}
return usedLines.join('\n');
}
/**
* Check if code is syntactically complete.
* Used for multi-line input in console-style interfaces.
*
* @param code - The code to check.
* @returns The completeness status and suggested indentation.
*/
isComplete(code: string): IIsCompleteResult {
if (code.trim().length === 0) {
return { status: 'complete' };
}
try {
parseScript(code, {
ranges: true,
module: true
});
return { status: 'complete' };
} catch (e: any) {
const message = e.message || '';
// Common patterns indicating incomplete code
const incompletePatterns = [
/unexpected end of input/i,
/unterminated string/i,
/unterminated template/i,
/unexpected token.*eof/i,
/expected.*but.*end/i
];
for (const pattern of incompletePatterns) {
if (pattern.test(message)) {
// Determine indentation for next line
const lines = code.split('\n');
const lastLine = lines[lines.length - 1];
const currentIndent = lastLine.match(/^(\s*)/)?.[1] || '';
// Add more indent if we're opening a block
const opensBlock = /[{([]$/.test(lastLine.trim());
const indent = opensBlock ? currentIndent + ' ' : currentIndent;
return { status: 'incomplete', indent };
}
}
// Syntax error that's not about incompleteness
return { status: 'invalid' };
}
}
/**
* Inspect an object at the cursor position.
* Returns documentation/type information for tooltips.
*
* @param code - The code containing the expression to inspect.
* @param cursorPos - The cursor position in the code.
* @param detailLevel - The level of detail (0 for basic, higher for more).
* @returns The inspection result with documentation data.
*/
inspect(
code: string,
cursorPos: number,
detailLevel: KernelMessage.IInspectRequestMsg['content']['detail_level'] = 0
): IInspectResult {
// Extract the word/expression at cursor position
const expression = this._extractExpressionAtCursor(code, cursorPos);
if (!expression) {
return {
status: 'ok',
found: false,
data: {},
metadata: {}
};
}
try {
// Try to evaluate the expression in the global scope
const evalFunc = this._createScopedFunction(
'scope',
`with(scope) { return ${expression}; }`
) as (scope: any) => any;
const value = evalFunc(this._globalScope);
// Build inspection data
const inspectionData = this._buildInspectionData(
expression,
value,
detailLevel
);
// Add predefined documentation if available
const doc = this.getBuiltinDocumentation(expression);
if (doc) {
const mdContent = inspectionData['text/markdown'] || '';
inspectionData['text/markdown'] = mdContent + `\n\n---\n\n${doc}`;
const plainContent = inspectionData['text/plain'] || '';
inspectionData['text/plain'] = plainContent + `\n\nDoc: ${doc}`;
}
return {
status: 'ok',
found: true,
data: inspectionData,
metadata: {}
};
} catch {
// Try to provide info even if we can't evaluate
return this.inspectBuiltin(expression, detailLevel);
}
}
/**
* Provide inspection info for built-in objects.
* First tries runtime lookup, then falls back to predefined docs.
*
* @param expression - The expression to look up.
* @param detailLevel - The level of detail requested.
* @returns The inspection result.
*/
protected inspectBuiltin(
expression: string,
detailLevel: number
): IInspectResult {
// First, try to find the expression in the global scope at runtime
const runtimeResult = this._inspectAtRuntime(expression, detailLevel);
if (runtimeResult.found) {
return runtimeResult;
}
// Fall back to predefined documentation
const doc = this.getBuiltinDocumentation(expression);
if (doc) {
return {
status: 'ok',
found: true,
data: {
'text/plain': `${expression}: ${doc}`,
'text/markdown': `**${expression}**\n\n${doc}`
},
metadata: {}
};
}
// Try to find similar names in global scope for suggestions
const suggestions = this._findSimilarNames(expression);
if (suggestions.length > 0) {
return {
status: 'ok',
found: true,
data: {
'text/plain': `'${expression}' not found. Did you mean: ${suggestions.join(', ')}?`,
'text/markdown': `\`${expression}\` not found.\n\n**Did you mean:**\n${suggestions.map(s => `- \`${s}\``).join('\n')}`
},
metadata: {}
};
}
return {
status: 'ok',
found: false,
data: {},
metadata: {}
};
}
/**
* Get predefined documentation for built-in JavaScript objects.
* Subclasses can override this to add domain-specific documentation.
*
* @param expression - The expression to get documentation for.
* @returns The documentation string, or null if not found.
*/
protected getBuiltinDocumentation(expression: string): string | null {
// Common JavaScript built-ins documentation
const builtins: Record<string, string> = {
console:
'The console object provides access to the browser debugging console.',
Math: 'The Math object provides mathematical constants and functions.',
JSON: 'The JSON object provides methods for parsing and stringifying JSON.',
Array:
'The Array object is used to store multiple values in a single variable.',
Object: "The Object class represents one of JavaScript's data types.",
String:
'The String object is used to represent and manipulate a sequence of characters.',
Number: 'The Number object is a wrapper object for numeric values.',
Date: 'The Date object represents a single moment in time.',
Promise:
'The Promise object represents the eventual completion of an async operation.',
Map: 'The Map object holds key-value pairs and remembers the original insertion order.',
Set: 'The Set object lets you store unique values of any type.'
};
return builtins[expression] ?? null;
}
/**
* Add code to export top-level variables to global scope.
*/
private _addToGlobalThisCode(key: string, identifier = key): string {
// Keep declarations on both globalThis and this for compatibility with
// different runtime invocation paths.
return `globalThis["${key}"] = this["${key}"] = ${identifier};`;
}
/**
* Create a function using the runtime realm's Function constructor.
*/
private _createScopedFunction(...args: string[]): JSCallable {
const scopeFunction = this._globalScope.Function;
const functionConstructor =