-
-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathindex.ts
More file actions
4480 lines (4088 loc) · 136 KB
/
Copy pathindex.ts
File metadata and controls
4480 lines (4088 loc) · 136 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
import ts from 'typescript';
import {
JupyterFrontEnd,
JupyterFrontEndPlugin
} from '@jupyterlab/application';
import { ISettingRegistry } from '@jupyterlab/settingregistry';
import {
Dialog,
MainAreaWidget,
Notification,
showDialog,
showErrorMessage,
ICommandPalette,
IToolbarWidgetRegistry,
ToolbarButton
} from '@jupyterlab/apputils';
import {
ILogConsoleTracker,
ILogEntryActionRegistry,
type ILogEntryActionMessage
} from 'jupyterlab-js-logs';
import { Signal } from '@lumino/signaling';
import { DocumentRegistry, IDocumentWidget } from '@jupyterlab/docregistry';
import { FileEditor, IEditorTracker } from '@jupyterlab/fileeditor';
import { IFileBrowserFactory } from '@jupyterlab/filebrowser';
import { ILauncher } from '@jupyterlab/launcher';
import { IMainMenu } from '@jupyterlab/mainmenu';
import {
IFrame,
fileUploadIcon,
infoIcon,
offlineBoltIcon,
SidePanel
} from '@jupyterlab/ui-components';
import { IDocumentManager } from '@jupyterlab/docmanager';
import { PathExt } from '@jupyterlab/coreutils';
import { Contents } from '@jupyterlab/services';
import { ICompletionProviderManager } from '@jupyterlab/completer';
import { PluginLoader, PluginLoadingError } from './loader';
import { PluginTranspiler } from './transpiler';
import { javaScriptKernelLspPlugins } from './javascript-kernel-lsp/integration';
import { loadKnownModule } from './modules';
import {
discoverFederatedKnownModules,
type IKnownModule,
listKnownModules,
registerCoreKnownModules,
registerKnownModule
} from './known-modules';
import { formatErrorWithResult } from './errors';
import { ImportResolver } from './resolver';
import { IRequireJS, RequireJSLoader } from './requirejs';
import {
type CommandInsertMode,
filterCommandRecords,
filterTokenRecords,
TokenSidebar
} from './token-sidebar';
import { ExampleSidebar, filterExampleRecords } from './example-sidebar';
import { LoadedPluginsSidebar } from './loaded-plugins-sidebar';
import { createFloatingUrlLoadHint } from './components/url-load-hint';
import { loadOnSaveToggleIcon, runTileIcon, tokenSidebarIcon } from './icons';
import {
CommandCompletionProvider,
getCommandArgumentCount,
getCommandArgumentDocumentation,
type ICommandArgumentDocumentation,
getCommandRecords
} from './command-completion';
import { ContentUtils } from './contents';
import {
ensurePluginActivateAppContext,
findPluginActivateAppParameterName,
insertImportStatement,
insertTokenDependency,
parseTokenReference
} from './token-insertion';
import { downloadArchive, IArchiveEntry } from './archive';
import { createTemplateArchive } from './export-template';
import {
hasPluginPlaygroundTourSupport,
launchPluginPlaygroundTour,
PLUGIN_PLAYGROUND_TOUR_MISSING_HINT
} from './tour';
import {
DEFAULT_EXPORT_ARCHIVE_FORMAT,
EXPORT_EXTENSION_TOOLBAR_ITEM,
ExportToolbarController,
type ExportArchiveFormat
} from './export-toolbar';
import {
SHARE_LINK_TOOLBAR_ITEM,
SHARE_VIA_LINK_ARGS_SCHEMA,
ShareViaLinkController,
type IPluginShareResult
} from './share-via-link-controller';
import { createPythonWheelArchive } from './wheel';
import { ReadonlyPartialJSONObject, Token } from '@lumino/coreutils';
import { AccordionPanel, MenuBar, Widget } from '@lumino/widgets';
import { IPlugin } from '@lumino/application';
export type { IPluginShareResult } from './share-via-link-controller';
namespace CommandIDs {
export const createNewFile = 'plugin-playground:create-new-plugin';
export const createNewFileWithAI =
'plugin-playground:create-new-plugin-with-ai';
export const takeTour = 'plugin-playground:take-tour';
export const createNewFileFromNotebookTree =
'plugin-playground:create-new-plugin-from-notebook-tree';
export const createNewFileWithAIFromNotebookTree =
'plugin-playground:create-new-plugin-with-ai-from-notebook-tree';
export const takeTourFromNotebookTree =
'plugin-playground:take-tour-from-notebook-tree';
export const loadCurrentAsExtension = 'plugin-playground:load-as-extension';
export const exportAsExtension = 'plugin-playground:export-as-extension';
export const shareViaLink = 'plugin-playground:share-via-link';
export const openJSImportExplorer = 'plugin-playground:open-js-explorer';
export const listTokens = 'plugin-playground:list-tokens';
export const listCommands = 'plugin-playground:list-commands';
export const listExtensionExamples =
'plugin-playground:list-extension-examples';
}
type PluginLoadStatus =
| 'loaded'
| 'editor-not-active'
| 'loading-failed'
| 'autostart-failed';
interface IPluginLoadResult {
status: PluginLoadStatus;
ok: boolean;
path: string | null;
pluginIds: string[];
transpiled: boolean | null;
message?: string;
skippedAutoStartPluginIds?: string[];
}
interface IPluginLoadQueueOptions {
notifyResult?: boolean;
}
/**
* Result metadata returned by export command executions.
*/
interface IPluginExportResult {
ok: boolean;
archiveName: string | null;
rootPath: string | null;
fileCount: number;
message?: string;
}
/**
* Fully resolved context required to build an export archive.
*/
interface IResolvedExportContext {
archiveName: string;
rootPath: string;
archiveEntries: IArchiveEntry[];
usedTemplate: boolean;
}
interface ILayoutHideSelection {
hideAll: boolean;
hideMenu: boolean;
hideStatusBar: boolean;
}
const PLUGIN_TEMPLATE = `import {
JupyterFrontEnd,
JupyterFrontEndPlugin,
} from '@jupyterlab/application';
/**
* This is an example hello world plugin.
* Open Command Palette with Ctrl+Shift+C
* (Command+Shift+C on Mac) and select
* "Load Current File as Extension"
*/
const plugin: JupyterFrontEndPlugin<void> = {
id: 'hello-world:plugin',
autoStart: true,
activate: (app: JupyterFrontEnd) => {
alert('Hello World!');
},
};
export default plugin;
`;
interface IPrivateServiceStore {
_serviceMap?: Map<Token<string>, string>;
_services?: Map<Token<string>, string>;
_delegate?: IPrivateServiceStore | null;
pluginRegistry?: IPrivatePluginRegistry | null;
}
interface IPrivatePluginRegistry {
_services?: Map<Token<string>, string>;
_plugins?: Map<string, IPrivatePluginData>;
}
interface IPrivatePluginData {
provides?: Token<string> | null;
requires?: Token<string>[];
optional?: Token<string>[];
description?: unknown;
plugin?: {
description?: unknown;
};
}
const EXTENSION_EXAMPLES_ROOT = 'extension-examples';
const LIST_QUERY_ARGS_SCHEMA = {
type: 'object',
additionalProperties: false,
properties: {
query: {
type: 'string',
description:
'Optional filter text. Matches records case-insensitively by visible text fields (such as id, label, caption, name, or description, depending on record type).'
}
}
};
const EXPORT_AS_EXTENSION_ARGS_SCHEMA = {
type: 'object',
additionalProperties: false,
properties: {
path: {
type: 'string',
description:
'Optional contents path of the file to export. When omitted, the active editor file is used.'
},
format: {
type: 'string',
enum: ['zip', 'wheel'],
description:
'Optional archive format (default: "zip"). Use "zip" for folder export or "wheel" for a Python package (.whl).'
}
}
};
const CREATE_PLUGIN_ARGS_SCHEMA = {
type: 'object',
additionalProperties: false,
properties: {
cwd: {
type: 'string',
description:
'Optional current working directory. Used as the default parent directory when `path` is not provided and as the base for relative `path` values.'
},
path: {
type: 'string',
description:
'Optional file path. Relative paths are resolved from the current working directory; paths starting with "/" are resolved from the workspace root. If no extension is provided, ".ts" is appended.'
}
}
};
const CREATE_PLUGIN_FROM_NOTEBOOK_TREE_ARGS_SCHEMA = {
type: 'object',
additionalProperties: false,
properties: {
cwd: {
type: 'string',
description:
'Optional current working directory used as the default parent directory for the new file.'
}
}
};
const LOAD_AS_EXTENSION_TOOLBAR_ITEM = 'load-as-extension';
const LOAD_ON_SAVE_TOGGLE_TOOLBAR_ITEM = 'plugin-playground-load-on-save';
const LOAD_ON_SAVE_CHECKBOX_LABEL = 'Run on save';
const LOAD_ON_SAVE_SETTING = 'loadOnSave';
const COMMAND_INSERT_DEFAULT_MODE_SETTING = 'commandInsertDefaultMode';
const LOAD_ON_SAVE_ENABLED_DESCRIPTION =
'Toggle auto-loading this file as an extension on save';
const LOAD_ON_SAVE_DISABLED_DESCRIPTION =
'Auto load on save is available for JavaScript and TypeScript files';
const JUPYTERLITE_AI_OPEN_OR_REVEAL_CHAT_COMMAND =
'@jupyterlite/ai:open-or-reveal-chat';
const JUPYTERLITE_AI_OPEN_SETTINGS_COMMAND = '@jupyterlite/ai:open-settings';
const JUPYTERLITE_AI_SETTINGS_MODEL_PLUGIN_ID =
'@jupyterlite/ai:settings-model';
const JUPYTERLITE_AI_INSTALL_HINT =
'JupyterLite AI is unavailable. Install the jupyterlite-ai extension and reload the application.';
const JUPYTERLITE_AI_PROVIDER_SETUP_HINT = 'No AI provider configured.';
const ASK_AI_LOG_ENTRY_ACTION_ID = 'plugin-playground:ask-ai-log-entry';
const LOG_ENTRY_PROMPT_MAX_OUTPUT_LENGTH = 8000;
type JupyterLiteAIErrorCode = 'install-unavailable' | 'provider-setup-required';
type JupyterLiteAIChatOpenStatus =
| 'opened'
| 'provider-setup-required'
| 'install-unavailable'
| 'failed';
class JupyterLiteAIError extends Error {
constructor(readonly code: JupyterLiteAIErrorCode, message: string) {
super(message);
this.name = 'JupyterLiteAIError';
}
}
const DEFAULT_COMMAND_INSERT_MODE: CommandInsertMode = 'insert';
const ARCHIVE_EXCLUDED_DIRECTORIES = new Set([
'.git',
'.ipynb_checkpoints',
'__pycache__',
'node_modules'
]);
const ARCHIVE_FILE_READ_CONCURRENCY = 8;
const HIDE_QUERY_KEY = 'hide';
const HIDE_QUERY_VALUE_ALL = 'all';
const HIDE_QUERY_VALUE_MENU = 'menu';
const HIDE_QUERY_VALUE_STATUSBAR = 'statusbar';
const EMPTY_LAYOUT_HIDE_SELECTION: ILayoutHideSelection = {
hideAll: false,
hideMenu: false,
hideStatusBar: false
};
const URL_LOADED_EDITOR_HINT_CLASS = 'jp-PluginPlayground-urlLoadedEditorHint';
const URL_LOADED_EDITOR_HINT_TITLE = 'Load as Extension';
const URL_LOADED_EDITOR_HINT_MESSAGE =
'Run this shared file in the playground.';
const URL_LOADED_EDITOR_HINT_DISMISS_LABEL = 'Close load as extension hint';
const NOTEBOOK_FILE_BROWSER_FACTORY = 'FileBrowser';
const NOTEBOOK_NEW_DROPDOWN_TOOLBAR_ITEM = 'new-dropdown';
const NOTEBOOK_TREE_OPEN_SIDEBAR_KEY =
'plugin-playground:open-sidebar-from-tree';
const NOTEBOOK_TREE_OPEN_AI_CHAT_KEY =
'plugin-playground:open-ai-chat-from-tree';
const DYNAMIC_SETTINGS_STORAGE_KEY_PREFIX =
'plugin-playground:dynamic-settings:';
const NOTEBOOK_SHELL_PLUGIN_ID =
'@jupyter-notebook/application-extension:shell';
const NOTEBOOK_TREE_WIDGET_PLUGIN_ID =
'@jupyter-notebook/tree-extension:widget';
export interface IPluginPlayground {
registerKnownModule(known: IKnownModule): Promise<void>;
shareViaLink(path?: string): Promise<IPluginShareResult>;
}
export const IPluginPlayground = new Token<IPluginPlayground>(
'@jupyterlab/plugin-playground:IPluginPlayground'
);
class PluginPlayground {
constructor(
protected app: JupyterFrontEnd,
protected settingRegistry: ISettingRegistry,
commandPalette: ICommandPalette,
protected editorTracker: IEditorTracker,
protected fileBrowserFactory: IFileBrowserFactory | null,
launcher: ILauncher | null,
protected documentManager: IDocumentManager | null,
protected settings: ISettingRegistry.ISettings,
protected requirejs: IRequireJS,
toolbarWidgetRegistry: IToolbarWidgetRegistry,
protected logConsoleTracker: ILogConsoleTracker | null
) {
registerCoreKnownModules();
this._layoutHideFromInitialUrl =
typeof window !== 'undefined'
? this._layoutHideSelectionFromUrl(window.location.href)
: EMPTY_LAYOUT_HIDE_SELECTION;
this._shareViaLinkController = new ShareViaLinkController({
app: this.app,
editorTracker: this.editorTracker,
fileBrowserFactory: this.fileBrowserFactory,
settings: this.settings,
commandId: CommandIDs.shareViaLink,
readSourceFileForExport: this._readSourceFileForExport.bind(this),
collectArchiveFilePaths: this._collectArchiveFilePaths.bind(this),
mapWithConcurrency: this._mapWithConcurrency.bind(this),
relativePath: this._relativePath.bind(this),
joinPath: this._joinPath.bind(this),
onShowSharedFileToolbarCue: this._showSharedFileToolbarCue.bind(this)
});
this._installDynamicSettingsConnectorShim();
this._restoreDynamicSettingPluginsFromStorage();
loadKnownModule('@jupyter-widgets/base').then((module: any) => {
// Define the widgets base module for RequireJS (left for compatibility only)
requirejs.define('@jupyter-widgets/base', [], () => module);
});
app.commands.addCommand(CommandIDs.loadCurrentAsExtension, {
label: 'Load Current File As Extension',
caption:
'Load the active editor file as an extension for plugin development',
describedBy: { args: null },
icon: args => (args['isPalette'] ? undefined : runTileIcon),
isEnabled: () => {
const currentWidget = editorTracker.currentWidget;
if (!currentWidget || currentWidget !== app.shell.currentWidget) {
return false;
}
return this._isSupportedPluginSourceFile(
ContentUtils.normalizeContentsPath(currentWidget.context.path)
);
},
isVisible: () => {
const currentWidget = editorTracker.currentWidget;
if (!currentWidget || currentWidget !== app.shell.currentWidget) {
return false;
}
return this._isSupportedPluginSourceFile(
ContentUtils.normalizeContentsPath(currentWidget.context.path)
);
},
execute: async () => {
const currentWidget = editorTracker.currentWidget;
if (currentWidget && currentWidget === app.shell.currentWidget) {
if (this._sharedFileCueWidgetId === currentWidget.id) {
this._dismissSharedFileCue?.();
}
const currentText = currentWidget.context.model.toString();
return this._queuePluginLoad(currentText, currentWidget.context.path);
}
return {
status: 'editor-not-active',
ok: false,
path: null,
pluginIds: [],
transpiled: null,
message: 'No active editor is available.'
} as IPluginLoadResult;
}
});
app.commands.addCommand(CommandIDs.exportAsExtension, {
label: 'Export Plugin Folder As Extension',
caption:
'Download the active plugin folder as an extension archive (.zip or .whl)',
describedBy: { args: EXPORT_AS_EXTENSION_ARGS_SCHEMA },
icon: args => (args['isPalette'] ? undefined : fileUploadIcon),
isEnabled: () => this.documentManager !== null,
execute: async args => {
const exportFormat: ExportArchiveFormat =
args.format === 'wheel' ? 'wheel' : DEFAULT_EXPORT_ARCHIVE_FORMAT;
const requestedPath =
typeof args.path === 'string'
? ContentUtils.normalizeContentsPath(args.path)
: '';
if (requestedPath) {
return this._exportAsExtension(
requestedPath,
undefined,
exportFormat
);
}
const currentWidget = editorTracker.currentWidget;
if (!currentWidget || currentWidget !== app.shell.currentWidget) {
return {
ok: false,
archiveName: null,
rootPath: null,
fileCount: 0,
message:
'No active editor is available. Pass a path argument to export a specific file.'
} as IPluginExportResult;
}
return this._exportAsExtension(
ContentUtils.normalizeContentsPath(currentWidget.context.path),
currentWidget.context.model.toString(),
exportFormat
);
}
});
app.commands.addCommand(CommandIDs.shareViaLink, {
label: this._shareViaLinkController.commandLabel.bind(
this._shareViaLinkController
),
caption: this._shareViaLinkController.commandCaption.bind(
this._shareViaLinkController
),
describedBy: { args: SHARE_VIA_LINK_ARGS_SCHEMA },
icon: args =>
args['isPalette']
? undefined
: this._shareViaLinkController.commandIcon(args),
isEnabled: this._shareViaLinkController.isCommandEnabled.bind(
this._shareViaLinkController
),
execute: this._shareViaLinkController.executeCommand.bind(
this._shareViaLinkController
)
});
toolbarWidgetRegistry.addFactory<IDocumentWidget<FileEditor>>(
'Editor',
SHARE_LINK_TOOLBAR_ITEM,
this._shareViaLinkController.createToolbarWidget.bind(
this._shareViaLinkController
)
);
toolbarWidgetRegistry.addFactory<IDocumentWidget<FileEditor>>(
'Editor',
LOAD_AS_EXTENSION_TOOLBAR_ITEM,
widget => this._createLoadAsExtensionToolbarWidget(widget)
);
toolbarWidgetRegistry.addFactory<IDocumentWidget<FileEditor>>(
'Editor',
LOAD_ON_SAVE_TOGGLE_TOOLBAR_ITEM,
widget => this._createLoadOnSaveToggleWidget(widget)
);
toolbarWidgetRegistry.addFactory<IDocumentWidget<FileEditor>>(
'Editor',
EXPORT_EXTENSION_TOOLBAR_ITEM,
widget =>
this._exportToolbar.createWidget({
editorWidget: widget,
hasDocumentManager: () => this.documentManager !== null,
onExport: async format => {
return (await this.app.commands.execute(
CommandIDs.exportAsExtension,
{
format
}
)) as IPluginExportResult;
}
})
);
editorTracker.widgetAdded.connect(
(_sender: IEditorTracker, widget: IDocumentWidget<FileEditor>) => {
const onSaveState = (
_context: DocumentRegistry.Context,
state: DocumentRegistry.SaveState
) => {
const normalizedPath = ContentUtils.normalizeContentsPath(
widget.context.path
);
if (state === 'completed' && this._shouldLoadOnSave(normalizedPath)) {
const currentText = widget.context.model.toString();
void this._queuePluginLoad(currentText, widget.context.path, {
notifyResult: false
});
}
};
widget.context.saveState.connect(onSaveState);
widget.disposed.connect(() => {
widget.context.saveState.disconnect(onSaveState);
});
}
);
commandPalette.addItem({
command: CommandIDs.loadCurrentAsExtension,
category: 'Plugin Playground',
args: { isPalette: true }
});
commandPalette.addItem({
command: CommandIDs.exportAsExtension,
category: 'Plugin Playground',
args: { isPalette: true }
});
commandPalette.addItem({
command: CommandIDs.shareViaLink,
category: 'Plugin Playground',
args: { isPalette: true }
});
app.commands.addCommand(CommandIDs.openJSImportExplorer, {
label: 'Open Packages Reference',
caption: 'Browse package docs, repository links, and package metadata.',
describedBy: { args: null },
execute: async () => {
await app.restored;
this._openPackagesReference();
}
});
commandPalette.addItem({
command: CommandIDs.openJSImportExplorer,
category: 'Plugin Playground',
args: {}
});
app.commands.addCommand(CommandIDs.createNewFile, {
label: args =>
args['isPalette']
? 'Plugin Playground: Start from File'
: 'Start from File',
caption:
'Create a new TypeScript plugin file and open the playground sidebar',
describedBy: { args: CREATE_PLUGIN_ARGS_SCHEMA },
icon: args => (args['isPalette'] ? undefined : tokenSidebarIcon),
execute: async args => {
const rawPathArg =
typeof args.path === 'string' ? args.path.trim() : '';
const isRootRelativePath = rawPathArg.startsWith('/');
const rawCwdArg = typeof args.cwd === 'string' ? args.cwd.trim() : '';
const normalizedCwdArg = ContentUtils.normalizeContentsPath(rawCwdArg);
const createInPath =
!isRootRelativePath && normalizedCwdArg ? normalizedCwdArg : '';
const model = await app.serviceManager.contents.newUntitled({
...(createInPath ? { path: createInPath } : {}),
type: 'file',
ext: 'ts'
});
let openPath = model.path;
const normalizedPathArg =
ContentUtils.normalizeContentsPath(rawPathArg);
if (normalizedPathArg) {
const baseDirectory = ContentUtils.normalizeContentsPath(
PathExt.dirname(model.path)
);
let targetPath = isRootRelativePath
? normalizedPathArg
: ContentUtils.normalizeContentsPath(
PathExt.join(baseDirectory, normalizedPathArg)
);
if (!/\.[^/]+$/.test(targetPath)) {
targetPath = `${targetPath}.ts`;
}
if (targetPath !== model.path) {
const targetDirectory = ContentUtils.normalizeContentsPath(
PathExt.dirname(targetPath)
).replace(/^\.$/, '');
if (targetDirectory) {
await ContentUtils.ensureContentsDirectory(
app.serviceManager,
targetDirectory
);
}
openPath = (
await app.serviceManager.contents.rename(model.path, targetPath)
).path;
}
}
await app.commands.execute('docmanager:open', {
path: openPath,
factory: 'Editor'
});
const normalizedOpenPath = ContentUtils.normalizeContentsPath(openPath);
let widget: IDocumentWidget<FileEditor> | null = null;
editorTracker.forEach(candidate => {
if (
!widget &&
ContentUtils.normalizeContentsPath(candidate.context.path) ===
normalizedOpenPath
) {
widget = candidate;
}
});
if (!widget) {
widget = editorTracker.currentWidget;
}
const activeWidget = widget;
if (activeWidget) {
activeWidget.content.ready.then(() => {
activeWidget.content.model.sharedModel.setSource(PLUGIN_TEMPLATE);
});
}
this._openPlaygroundSidebar();
return activeWidget;
}
});
commandPalette.addItem({
command: CommandIDs.createNewFile,
category: 'Plugin Playground',
args: { isPalette: true }
});
app.commands.addCommand(CommandIDs.createNewFileWithAI, {
label: args =>
args['isPalette']
? 'Plugin Playground: Build with AI'
: 'Build with AI',
caption:
'Create a new TypeScript plugin file and open AI chat setup for guided building',
describedBy: { args: CREATE_PLUGIN_ARGS_SCHEMA },
icon: args => (args['isPalette'] ? undefined : offlineBoltIcon),
execute: async args => {
const chatStatus = await this._openJupyterLiteAIChatWithSetupFallback();
if (chatStatus === 'provider-setup-required') {
return null;
}
const activeWidget = (await app.commands.execute(
CommandIDs.createNewFile,
args
)) as IDocumentWidget<FileEditor> | null;
if (chatStatus === 'opened') {
await this._openJupyterLiteAIChatWithSetupFallback();
}
return activeWidget;
}
});
commandPalette.addItem({
command: CommandIDs.createNewFileWithAI,
category: 'Plugin Playground',
args: { isPalette: true }
});
app.commands.addCommand(CommandIDs.takeTour, {
label: args =>
args['isPalette']
? 'Plugin Playground: Take the Tour'
: 'Take the Tour',
caption:
'Open a guided walkthrough of Plugin Playground, extension examples, and AI setup',
describedBy: { args: CREATE_PLUGIN_ARGS_SCHEMA },
icon: args => (args['isPalette'] ? undefined : infoIcon),
execute: async args => {
if (!hasPluginPlaygroundTourSupport(app)) {
Notification.warning(
`${PLUGIN_PLAYGROUND_TOUR_MISSING_HINT} Install "jupyterlab-tour" and reload JupyterLab.`,
{
autoClose: 7000
}
);
return {
ok: false,
message: PLUGIN_PLAYGROUND_TOUR_MISSING_HINT
};
}
try {
await this._preparePluginPlaygroundTourContext(args);
await launchPluginPlaygroundTour(app);
return { ok: true };
} catch (error) {
const message =
error instanceof Error ? error.message : String(error);
Notification.warning(`Could not start the tour: ${message}`, {
autoClose: 7000
});
return {
ok: false,
message
};
}
}
});
commandPalette.addItem({
command: CommandIDs.takeTour,
category: 'Plugin Playground',
args: { isPalette: true }
});
app.commands.addCommand(CommandIDs.listTokens, {
label: 'List Extension Tokens (Playground)',
caption: 'List available token strings',
describedBy: { args: LIST_QUERY_ARGS_SCHEMA },
execute: args => {
const query = typeof args.query === 'string' ? args.query.trim() : '';
const tokens = this._getTokenRecords();
const items = filterTokenRecords(tokens, query);
return {
query,
total: tokens.length,
count: items.length,
items: [...items]
};
}
});
app.commands.addCommand(CommandIDs.listCommands, {
label: 'List Extension Commands (Playground)',
caption: 'List available command IDs',
describedBy: { args: LIST_QUERY_ARGS_SCHEMA },
execute: args => {
const query = typeof args.query === 'string' ? args.query.trim() : '';
const commands = getCommandRecords(this.app);
const items = filterCommandRecords(commands, query);
return {
query,
total: commands.length,
count: items.length,
items: [...items]
};
}
});
app.commands.addCommand(CommandIDs.listExtensionExamples, {
label: 'List Extension Examples (Playground)',
caption: 'List available extension examples',
describedBy: { args: LIST_QUERY_ARGS_SCHEMA },
execute: async args => {
const query = typeof args.query === 'string' ? args.query.trim() : '';
const examples = await this._discoverExtensionExamples();
const items = filterExampleRecords(examples, query);
return {
query,
total: examples.length,
count: items.length,
items: [...items]
};
}
});
app.restored.then(async () => {
const settings = this.settings;
this._updateSettings(requirejs, settings);
this._refreshExtensionPoints();
const tokenSidebar = new TokenSidebar({
getTokens: this._getTokenRecords.bind(this),
getCommands: () => getCommandRecords(this.app),
getKnownModules: () => listKnownModules(),
getCommandArguments: commandId =>
getCommandArgumentDocumentation(this.app, commandId),
getCommandArgumentCount: commandId =>
getCommandArgumentCount(this.app, commandId),
discoverKnownModules: force => discoverFederatedKnownModules({ force }),
openDocumentationLink: this._openDocumentationLink.bind(this),
onInsertImport: this._insertTokenImport.bind(this),
isImportEnabled: this._canInsertImport.bind(this),
onSetCommandInsertMode: this._setCommandInsertMode.bind(this),
onInsertCommand: this._insertCommandExecution.bind(this),
getCommandInsertMode: () => this._commandInsertMode,
isCommandInsertEnabled: this._hasEditableEditor.bind(this)
});
this._tokenSidebar = tokenSidebar;
tokenSidebar.id = 'jp-plugin-token-sidebar';
tokenSidebar.title.label = 'Extension Points';
tokenSidebar.title.caption = 'Available extension points for plugin';
tokenSidebar.title.icon = tokenSidebarIcon;
const exampleSidebar = new ExampleSidebar({
fetchExamples: this._discoverExtensionExamples.bind(this),
onOpenExample: this._openExtensionExample.bind(this),
onOpenReadme: this._openExtensionExampleReadme.bind(this)
});
exampleSidebar.id = 'jp-plugin-example-sidebar';
exampleSidebar.title.label = 'Extension Examples';
exampleSidebar.title.caption =
'Browse plugin examples from jupyterlab/extension-examples';
const loadedPluginsSidebar = new LoadedPluginsSidebar({
getLoadedPlugins: this._getLoadedPluginRecords.bind(this),
onDeactivate: this._deactivateLoadedPlugin.bind(this)
});
this._loadedPluginsSidebar = loadedPluginsSidebar;
loadedPluginsSidebar.id = 'jp-plugin-loaded-sidebar';
loadedPluginsSidebar.title.label = 'Currently Loaded Plugins';
loadedPluginsSidebar.title.caption =
'Playground-loaded plugins active in this session';
const playgroundSidebar = new SidePanel();
playgroundSidebar.id = 'jp-plugin-playground-sidebar';
playgroundSidebar.title.caption = 'Plugin Playground helper panels';
playgroundSidebar.title.icon = tokenSidebarIcon;
playgroundSidebar.addWidget(tokenSidebar);
playgroundSidebar.addWidget(exampleSidebar);
playgroundSidebar.addWidget(loadedPluginsSidebar);
this.app.shell.add(playgroundSidebar, 'right', { rank: 650 });
this._playgroundSidebar = playgroundSidebar;
this._expandPlaygroundSidebarSections();
if (typeof window !== 'undefined') {
const shouldOpenFromTree = window.sessionStorage.getItem(
NOTEBOOK_TREE_OPEN_SIDEBAR_KEY
);
if (shouldOpenFromTree === '1') {
window.sessionStorage.removeItem(NOTEBOOK_TREE_OPEN_SIDEBAR_KEY);
this._openPlaygroundSidebar();
}
const shouldOpenAIChatFromTree = window.sessionStorage.getItem(
NOTEBOOK_TREE_OPEN_AI_CHAT_KEY
);
if (shouldOpenAIChatFromTree === '1') {
window.sessionStorage.removeItem(NOTEBOOK_TREE_OPEN_AI_CHAT_KEY);
void this._openJupyterLiteAIChatWithSetupFallback();
}
}
app.shell.currentChanged?.connect(() => {
tokenSidebar.update();
});
editorTracker.currentChanged.connect(() => {
tokenSidebar.update();
});
app.commands.commandChanged.connect((_, args) => {
if (args.type === 'added' || args.type === 'removed') {
tokenSidebar.update();
}
if (
(args.type === 'added' || args.type === 'removed') &&
args.id === JUPYTERLITE_AI_OPEN_OR_REVEAL_CHAT_COMMAND
) {
void this._updateAskAILogEntryActionRegistration();
}
});
// add to the launcher
if (launcher && (settings.composite.showIconInLauncher as boolean)) {
launcher.add({
command: CommandIDs.createNewFile,
category: 'Plugin Playground',
rank: 1
});
launcher.add({
command: CommandIDs.createNewFileWithAI,
category: 'Plugin Playground',
rank: 2
});
launcher.add({
command: CommandIDs.takeTour,
category: 'Plugin Playground',
rank: 3
});
}
const urls = settings.composite.urls as string[];
for (const u of urls) {
await this._getModule(u);
}
const plugins = settings.composite.plugins as string[];
for (const t of plugins) {
await this._loadPlugin(t, null);
}
await this._shareViaLinkController.loadSharedPluginFromUrl();
await this._applyLayoutFromQuery();
settings.changed.connect(updatedSettings => {
this.settings = updatedSettings;
this._updateSettings(requirejs, updatedSettings);
tokenSidebar.update();
for (const refresh of this._loadOnSaveToggleRefreshers) {
refresh();
}
});
this._setupLogsBadge();
void this._updateAskAILogEntryActionRegistration();
});
}
private _isGlobalLoadOnSaveEnabled(): boolean {
return this.settings.get(LOAD_ON_SAVE_SETTING).composite === true;
}
private _isSupportedPluginSourceFile(path: string): boolean {
return /\.(?:js|jsx|ts|tsx)$/i.test(path);
}
private _shouldLoadOnSave(normalizedPath: string): boolean {
if (!this._isSupportedPluginSourceFile(normalizedPath)) {
return false;
}
if (this._isGlobalLoadOnSaveEnabled()) {
return true;
}
return this._loadOnSaveByFile.has(normalizedPath);
}
private _createLoadAsExtensionToolbarWidget(
widget: IDocumentWidget<FileEditor>
): Widget {
const runButton = new ToolbarButton({
label: 'Run',
icon: runTileIcon,