-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextension.js
More file actions
1543 lines (1404 loc) · 68.4 KB
/
Copy pathextension.js
File metadata and controls
1543 lines (1404 loc) · 68.4 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
// extension.js - Explorer Dates
const vscode = require('vscode');
const env = (typeof process !== 'undefined' && process.env) ? process.env : {};
// FileDateDecorationProvider: loaded lazily from chunk at activation to keep core bundle small
// If chunks are not available at runtime, we fall back to the source provider synchronously in activation.
const { getLogger } = require('./src/utils/logger');
// Localization will be loaded lazily to reduce initial bundle size
let l10n;
async function ensureLocalization() {
if (!l10n) {
const mod = await import('./src/utils/localization.js');
l10n = mod.getLocalization();
}
return l10n;
}
const { fileSystem } = require('./src/filesystem/FileSystemAdapter');
const { registerCoreCommands } = require('./src/commands/coreCommands');
const { registerOnboardingCommands } = require('./src/commands/onboardingCommands');
const { registerMigrationCommands } = require('./src/commands/migrationCommands');
const { initializeTemplateStore } = require('./src/utils/templateStore');
const { SettingsMigrationManager } = require('./src/utils/settingsMigration');
const { ExtensionError, ERROR_CODES, ChunkLoadError, handleChunkFailure } = require('./src/utils/errors');
const {
isWebDiagnosticsEnabled,
diagLog,
recordCommandRegistration,
recordCommandInvocation,
recordCommandResult,
recordChunkEvent,
recordProviderEvent,
getWebDiagnosticsState
} = require('./src/utils/webDiagnostics');
// Prefer shared utils chunk when available (keeps core smaller)
let ensureDate;
try {
const shared = require('./src/chunks/utils-shared-chunk');
if (shared) ensureDate = shared.ensureDate;
} catch { /* ignore */ }
if (!ensureDate) { const dateHelpers = require('./src/utils/dateHelpers'); ensureDate = dateHelpers.ensureDate; }
const { WEB_CHUNK_GLOBAL_KEY, LEGACY_WEB_CHUNK_GLOBAL_KEY } = require('./src/constants');
const isWebEnvironment = () => {
try {
if (typeof process !== 'undefined' && process?.env?.VSCODE_WEB === 'true') return true;
} catch { /* ignore */ }
try {
return vscode?.env?.uiKind === vscode?.UIKind?.Web;
} catch {
return false;
}
};
if (isWebEnvironment() && typeof globalThis !== 'undefined' && !globalThis.__explorerDatesRuntimeCommands) {
try {
globalThis.__explorerDatesRuntimeCommands = require('./src/commands/runtimeCommands');
} catch {
// ignore: web runtime will fall back to chunk registry if available
}
}
let nodeFs = null;
let nodePath = null;
const webTextDecoder = typeof TextDecoder === 'function' ? new TextDecoder('utf-8') : null;
if (!isWebEnvironment()) {
try {
nodeFs = require('fs');
} catch {
nodeFs = null;
}
try {
nodePath = require('path');
} catch {
nodePath = null;
}
}
const AUTO_SUGGESTION_DELAY_MS = 3000;
function getCriticalChunks() {
return isWebEnvironment() ? [] : ['incrementalWorkers'];
}
function resolveDefaultDistPath() {
if (!nodePath || typeof nodePath.basename !== 'function' || typeof nodePath.join !== 'function') {
return null;
}
const currentDirName = nodePath.basename(__dirname);
if (currentDirName === 'dist') {
return __dirname;
}
return nodePath.join(__dirname, 'dist');
}
const DEFAULT_DIST_PATH = resolveDefaultDistPath();
// Lazy load large modules to reduce initial bundle size
// const { OnboardingManager } = require('./src/onboarding');
// const { WorkspaceTemplatesManager } = require('./src/workspaceTemplates');
// const { ExtensionApiManager } = require('./src/extensionApi');
// const { ExportReportingManager } = require('./src/exportReporting');
let fileDateProvider;
let logger;
let runtimeAutoSuggestionTimer = null;
let activeRuntimeManager = null;
let activeTeamPersistenceManager = null;
// In-memory cache to avoid races when marking workspace warnings during sync tests
const _warnedWorkspaces = new Set();
const ANALYSIS_WARNING_WORKSPACE_KEY = 'explorerDates.analysisCommandsDisabledWarningByWorkspace';
// Global WeakMap fallback to survive module reloads when the same context object is reused
if (typeof globalThis !== 'undefined' && !globalThis.__explorerDates_analysisWarningWeakMap) {
try { globalThis.__explorerDates_analysisWarningWeakMap = new WeakMap(); } catch { globalThis.__explorerDates_analysisWarningWeakMap = null; }
}
function getActiveLogger() {
if (!logger) {
logger = getLogger();
}
return logger;
}
function getWorkspaceId() {
const firstWorkspace = vscode.workspace.workspaceFolders?.[0];
return firstWorkspace?.uri?.toString() || 'global';
}
function hasShownAnalysisWarning(context) {
const workspaceId = getWorkspaceId();
const map = context?.globalState?.get ? context.globalState.get(ANALYSIS_WARNING_WORKSPACE_KEY, {}) : {};
// WeakMap fallback: map context -> persisted map so a reloaded module can find it for the same context object
const wm = (typeof globalThis !== 'undefined') ? globalThis.__explorerDates_analysisWarningWeakMap : null;
const wmMap = (wm && wm.has(context)) ? wm.get(context) : {};
return Boolean(map[workspaceId]) || Boolean(wmMap[workspaceId]) || _warnedWorkspaces.has(workspaceId);
}
async function setAnalysisWarningShown(context, value) {
const workspaceId = getWorkspaceId();
const map = context?.globalState?.get ? context.globalState.get(ANALYSIS_WARNING_WORKSPACE_KEY, {}) : {};
map[workspaceId] = value;
// update in-memory set immediately to avoid races
if (value) _warnedWorkspaces.add(workspaceId);
else _warnedWorkspaces.delete(workspaceId);
// update persistent map in globalThis as an immediate synchronous fallback
// Persist map to WeakMap fallback (if available) to survive module reloads for same context object
const wm = (typeof globalThis !== 'undefined') ? globalThis.__explorerDates_analysisWarningWeakMap : null;
if (wm && context) {
try {
wm.set(context, map);
} catch {
// ignore
}
}
await context.globalState.update(ANALYSIS_WARNING_WORKSPACE_KEY, map);
}
/**
* Enhanced Dynamic Loading System with Feature Flags
* Implements module federation for maximum bundle optimization
*/
const { registerFeatureFlagsGlobal } = require('./src/utils/featureFlagsBridge');
const featureFlagsModule = require('./src/featureFlags');
registerFeatureFlagsGlobal(featureFlagsModule);
const featureFlags = featureFlagsModule; // Get all exported methods including spread ones
const { setFeatureChunkResolver } = featureFlagsModule;
const { CHUNK_MAP, generateDevLoaderMap } = require('./src/shared/chunkMap');
// Chunk loading system for module federation
const sourceChunkLoader = (() => {
if (typeof process === 'undefined' || env.NODE_ENV === 'production') {
return null;
}
try {
const localRequire = eval('require');
return (chunkName) => {
try {
// Generate the map from shared chunk configuration
const map = generateDevLoaderMap(localRequire);
const chunk = map[chunkName]?.();
return chunk?.default || chunk || null;
} catch (error) {
const chunkError = new ExtensionError(
ERROR_CODES.CHUNK_LOAD_FAILED,
`Source chunk fallback failed for ${chunkName}`,
{ chunkName, source: 'development', error: error.message }
);
getActiveLogger().warn(chunkError.message, chunkError.context);
return null;
}
};
} catch {
return null;
}
})();
const chunkLoader = {
loadedChunks: new Map(),
distPath: DEFAULT_DIST_PATH,
extensionUri: null,
webChunkPromises: new Map(),
_webLoadedScripts: new Set(),
_missingChunks: new Set(),
_webChunkAliases: null,
initialize(context) {
if (nodePath) {
if (typeof context?.asAbsolutePath === 'function') {
this.distPath = context.asAbsolutePath('dist');
} else if (context?.extensionPath) {
this.distPath = nodePath.join(context.extensionPath, 'dist');
}
}
if (context?.extensionUri) {
this.extensionUri = context.extensionUri;
}
if (!this._webChunkAliases) {
this._webChunkAliases = this._buildWebChunkAliases();
}
},
async loadChunk(chunkName) {
if (this.loadedChunks.has(chunkName)) {
return this.loadedChunks.get(chunkName);
}
try {
if (isWebDiagnosticsEnabled()) {
recordChunkEvent(chunkName, 'load:start');
}
const chunk = isWebEnvironment() ? null : this._loadNodeChunk(chunkName);
if (isWebEnvironment()) {
const webChunk = this._getWebChunkRegistry()?.[chunkName] ?? null;
if (webChunk) {
this.loadedChunks.set(chunkName, webChunk);
getActiveLogger().info('Chunk loaded', { chunkName, target: 'web' });
if (isWebDiagnosticsEnabled()) {
recordChunkEvent(chunkName, 'load:success');
}
}
return webChunk;
}
if (chunk) {
this.loadedChunks.set(chunkName, chunk);
getActiveLogger().info('Chunk loaded', { chunkName, target: 'node' });
if (isWebDiagnosticsEnabled()) {
recordChunkEvent(chunkName, 'load:success');
}
}
return chunk;
} catch (error) {
if (isWebDiagnosticsEnabled()) {
recordChunkEvent(chunkName, 'load:failure', error);
}
const chunkError = error instanceof ExtensionError
? error
: new ExtensionError(
ERROR_CODES.CHUNK_LOAD_FAILED,
`Failed to load chunk ${chunkName}`,
{
chunkName,
target: isWebEnvironment() ? 'web' : 'node',
error: error?.message
}
);
getActiveLogger().warn(chunkError.message, chunkError.context);
return null;
}
},
assertChunkArtifacts(chunkNames = []) {
if (!nodeFs || !this.distPath || !Array.isArray(chunkNames) || chunkNames.length === 0) {
return;
}
const missing = chunkNames.filter((name) => !this._hasChunkArtifacts(name));
if (missing.length > 0) {
const error = new ChunkLoadError(
missing.join(', '),
'missing built artifacts',
{
recoverable: false,
context: {
chunkNames: missing,
distPath: this.distPath,
fix: 'Run "npm run package-chunks" before packaging or testing.'
}
}
);
handleChunkFailure(missing.join(', '), error, { userFacing: true });
throw error;
}
},
_hasChunkArtifacts(chunkName) {
if (!nodeFs || !this.distPath) {
return true;
}
const nodeChunkPath = nodePath.join(this.distPath, 'chunks', `${chunkName}.js`);
const webChunkPath = nodePath.join(this.distPath, 'web-chunks', `${chunkName}.js`);
// In web environment, only web chunks are required
// In Node environment, only node chunks are required
// This allows for platform-specific chunk exclusions
if (isWebEnvironment()) {
return nodeFs.existsSync(webChunkPath);
} else {
return nodeFs.existsSync(nodeChunkPath);
}
},
_loadNodeChunk(chunkName) {
if (nodeFs && nodePath && this.distPath) {
const builtChunkPath = nodePath.join(this.distPath, 'chunks', `${chunkName}.js`);
if (nodeFs.existsSync(builtChunkPath)) {
try {
let chunk = require(builtChunkPath);
if (chunk?.default) {
chunk = chunk.default;
}
return chunk;
} catch (error) {
const chunkError = new ExtensionError(
ERROR_CODES.CHUNK_LOAD_FAILED,
`Failed to require built chunk ${chunkName}`,
{ chunkName, path: builtChunkPath, error: error.message }
);
getActiveLogger().warn(chunkError.message, chunkError.context);
}
}
}
if (sourceChunkLoader) {
return sourceChunkLoader(chunkName);
}
this._markChunkMissing(chunkName);
return null;
},
async _loadWebChunk(chunkName) {
if (!this.extensionUri) {
const chunkError = new ExtensionError(
ERROR_CODES.CHUNK_LOAD_FAILED,
'Missing extensionUri for web chunk loading',
{ chunkName }
);
getActiveLogger().warn(chunkError.message, chunkError.context);
return null;
}
if (!this.webChunkPromises.has(chunkName)) {
const promise = (async () => {
await this._ensureWebChunkScript(chunkName);
const registry = this._getWebChunkRegistry();
const chunk = registry?.[chunkName];
if (!chunk) {
throw new Error(`Web chunk ${chunkName} failed to register`);
}
return chunk;
})();
this.webChunkPromises.set(chunkName, promise);
}
return this.webChunkPromises.get(chunkName);
},
async _ensureWebChunkScript(chunkName) {
if (this._webLoadedScripts.has(chunkName)) {
return;
}
const chunkUri = vscode.Uri.joinPath(this.extensionUri, 'dist', 'web-chunks', `${chunkName}.js`);
if (!vscode.workspace?.fs || !webTextDecoder) {
throw new Error('Workspace FS or TextDecoder unavailable for web chunk loading');
}
try {
const raw = await vscode.workspace.fs.readFile(chunkUri);
const source = webTextDecoder.decode(raw);
const webRequire = (moduleId) => this._webRequire(moduleId);
const evaluator = new Function('require', source);
evaluator.call(globalThis, webRequire);
this._syncChunkRegistryKeys();
this._webLoadedScripts.add(chunkName);
} catch (error) {
this._markChunkMissing(chunkName);
throw error;
}
},
_getWebChunkRegistry() {
const registry =
globalThis[WEB_CHUNK_GLOBAL_KEY] ||
globalThis[LEGACY_WEB_CHUNK_GLOBAL_KEY] ||
null;
if (registry) {
this._syncChunkRegistryKeys();
}
return registry;
},
_syncChunkRegistryKeys() {
const registry =
globalThis[WEB_CHUNK_GLOBAL_KEY] ||
globalThis[LEGACY_WEB_CHUNK_GLOBAL_KEY] ||
{};
if (!globalThis[WEB_CHUNK_GLOBAL_KEY]) {
globalThis[WEB_CHUNK_GLOBAL_KEY] = registry;
}
if (!globalThis[LEGACY_WEB_CHUNK_GLOBAL_KEY]) {
globalThis[LEGACY_WEB_CHUNK_GLOBAL_KEY] = registry;
}
},
_buildWebChunkAliases() {
const aliases = new Map();
const entries = Object.entries(CHUNK_MAP || {});
for (const [chunkName, chunkPath] of entries) {
const base = String(chunkPath || '').split('/').pop();
if (base) {
aliases.set(base, chunkName);
}
}
return aliases;
},
_resolveWebChunkAlias(moduleId) {
if (!moduleId) return null;
const cleaned = String(moduleId)
.replace(/^[.\\/]+/, '')
.replace(/\.js$/, '');
if (this._webChunkAliases && this._webChunkAliases.has(cleaned)) {
return this._webChunkAliases.get(cleaned);
}
const base = cleaned.split('/').pop();
if (this._webChunkAliases && this._webChunkAliases.has(base)) {
return this._webChunkAliases.get(base);
}
return null;
},
_webRequire(moduleId) {
if (moduleId === 'vscode') {
return vscode;
}
const registry = this._getWebChunkRegistry();
if (!registry) {
throw new Error(`Web require failed: registry unavailable for ${moduleId}`);
}
const alias = this._resolveWebChunkAlias(moduleId);
if (alias && registry[alias]) {
return registry[alias];
}
if (registry[moduleId]) {
return registry[moduleId];
}
if (moduleId === '../commands/runtimeCommands' || moduleId === './commands/runtimeCommands') {
if (typeof globalThis !== 'undefined' && globalThis.__explorerDatesRuntimeCommands) {
return globalThis.__explorerDatesRuntimeCommands;
}
}
throw new Error(`Web require unsupported: ${moduleId}`);
},
_markChunkMissing(chunkName) {
if (this._missingChunks.has(chunkName)) {
return;
}
this._missingChunks.add(chunkName);
const error = new ChunkLoadError(chunkName, 'artifact unavailable', {
recoverable: false,
context: {
chunkName,
distPath: this.distPath,
fix: 'Run "npm run package-chunks" to rebuild runtime chunks.'
}
});
getActiveLogger().error(error.message, error);
handleChunkFailure(chunkName, error, { userFacing: false });
}
};
/**
* Dynamic import for maximum bundle splitting with feature flags
*/
const dynamicImports = {
async loadOnboarding(context) {
const chunk = await featureFlags.onboarding();
if (!chunk) {
return null;
}
if (typeof chunk.createOnboardingManager === 'function') {
return chunk.createOnboardingManager(context);
}
if (chunk.OnboardingManager) {
return new chunk.OnboardingManager(context);
}
return null;
},
async loadExportReporting(context) {
const chunk = await featureFlags.exportReporting();
if (typeof chunk?.createExportReportingManager === 'function') {
return chunk.createExportReportingManager(context);
}
if (!chunk) {
return null;
}
return null;
},
async loadWorkspaceTemplates(context) {
const chunk = await featureFlags.workspaceTemplates();
if (typeof chunk?.createWorkspaceTemplatesManager === 'function') {
return chunk.createWorkspaceTemplatesManager(context);
}
if (chunk?.WorkspaceTemplatesManager) {
return new chunk.WorkspaceTemplatesManager(context);
}
return null;
},
async loadAnalysisCommands() {
return featureFlags.analysisCommands();
},
async loadExtensionApi(context) {
const chunk = await featureFlags.extensionApi();
if (!chunk) {
return null;
}
// Handle various chunk export patterns
if (typeof chunk === 'function') {
// Check if it's the createExtensionApiManager factory function
if (chunk.name === 'createExtensionApiManager') {
return chunk(context);
}
// Otherwise, might be the class itself
try {
return new chunk();
} catch {
// Failed to construct, return null
return null;
}
} else if (typeof chunk.createExtensionApiManager === 'function') {
return chunk.createExtensionApiManager(context);
} else if (chunk.ExtensionApiManager) {
return new chunk.ExtensionApiManager();
}
return null;
}
};
let onboardingManagerPromise = null;
let workspaceTemplatesManagerPromise = null;
let exportReportingManagerPromise = null;
let extensionApiManagerPromise = null;
function shouldPrimeOnboardingChunk(context) {
if (!context?.globalState) {
return true;
}
const hasShownWelcome = context.globalState.get('explorerDates.hasShownWelcome', false);
const hasCompletedSetup = context.globalState.get('explorerDates.hasCompletedSetup', false);
const storedVersion = context.globalState.get('explorerDates.onboardingVersion', '0.0.0');
const currentVersion = context.extension?.packageJSON?.version || '0.0.0';
if (!hasShownWelcome || !hasCompletedSetup) {
return true;
}
return isMajorVersionUpdate(storedVersion, currentVersion);
}
function isMajorVersionUpdate(previousVersion, currentVersion) {
const parseMajor = (version) => {
const [major = '0'] = (version || '').split('.');
const parsed = Number.parseInt(major, 10);
return Number.isFinite(parsed) ? parsed : 0;
};
const previousMajor = parseMajor(previousVersion);
const currentMajor = parseMajor(currentVersion);
return currentMajor > previousMajor;
}
function ensureOnboardingManager(context) {
if (!onboardingManagerPromise) {
onboardingManagerPromise = dynamicImports.loadOnboarding(context);
}
return onboardingManagerPromise;
}
function ensureWorkspaceTemplatesManager(context) {
if (!workspaceTemplatesManagerPromise) {
workspaceTemplatesManagerPromise = dynamicImports.loadWorkspaceTemplates(context);
}
return workspaceTemplatesManagerPromise;
}
function ensureExportReportingManager(context) {
if (!exportReportingManagerPromise) {
exportReportingManagerPromise = dynamicImports.loadExportReporting(context);
}
return exportReportingManagerPromise;
}
function ensureExtensionApiManager(context) {
if (!extensionApiManagerPromise) {
extensionApiManagerPromise = dynamicImports.loadExtensionApi(context);
}
return extensionApiManagerPromise;
}
function raiseChunkUnavailable(featureLabel, chunkName) {
const message = `${featureLabel} is not available because the required "${chunkName}" runtime chunk failed to load. Reinstall Explorer Dates or run "npm run package-chunks" and reload VS Code.`;
getActiveLogger().warn(message, { chunkName });
vscode.window.showErrorMessage(message);
const error = new ChunkLoadError(chunkName, 'chunk missing at runtime', {
recoverable: false,
context: { featureLabel }
});
throw error;
}
/**
* Generate comprehensive diagnostics webview HTML
*/
/**
* Initialize status bar integration
*/
function initializeStatusBar(context) {
const statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
statusBarItem.command = 'explorerDates.showFileDetails';
statusBarItem.tooltip = 'Click to show detailed file information';
// Update status bar when selection changes
const updateStatusBar = async () => {
try {
const activeEditor = vscode.window.activeTextEditor;
if (!activeEditor) {
statusBarItem.hide();
return;
}
const uri = activeEditor.document.uri;
if (uri.scheme !== 'file') {
statusBarItem.hide();
return;
}
const stat = await fileSystem.stat(uri);
const modified = ensureDate(stat.mtime);
const timeAgo = fileDateProvider._formatDateBadge(modified, 'smart');
const fileSize = fileDateProvider._formatFileSize(stat.size, 'auto');
statusBarItem.text = `$(clock) ${timeAgo} $(file) ${fileSize}`;
statusBarItem.show();
} catch (error) {
statusBarItem.hide();
logger.debug('Failed to update status bar', error);
}
};
// Listen for active editor changes and capture disposables
const editorChangeDisposable = vscode.window.onDidChangeActiveTextEditor(updateStatusBar);
const selectionChangeDisposable = vscode.window.onDidChangeTextEditorSelection(updateStatusBar);
// Initial update
updateStatusBar();
context.subscriptions.push(statusBarItem, editorChangeDisposable, selectionChangeDisposable);
return statusBarItem;
}
/**
* Extension activation function
* @param {vscode.ExtensionContext} context
*/
async function activate(context) {
try {
if (isWebDiagnosticsEnabled()) {
diagLog('info', 'Activation start', {
uiKind: vscode?.env?.uiKind,
isWeb: isWebEnvironment()
});
}
logger = getLogger();
l10n = await ensureLocalization();
context.subscriptions.push(l10n);
initializeTemplateStore(context);
chunkLoader.initialize(context);
chunkLoader.assertChunkArtifacts(getCriticalChunks());
setFeatureChunkResolver((chunkName) =>
isWebEnvironment()
? chunkLoader._loadWebChunk(chunkName)
: chunkLoader.loadChunk(chunkName)
);
const remoteName = vscode?.env?.remoteName || null;
const uiKind = vscode?.env?.uiKind || null;
const isWebRuntime = uiKind === vscode.UIKind.Web;
const workspaceSchemes = (vscode.workspace.workspaceFolders || [])
.map((folder) => folder?.uri?.scheme)
.filter(Boolean);
logger.info('Explorer Dates: Extension activated');
logger.info('Explorer Dates: Activation context', {
uiKind,
remoteName,
isWeb: isWebRuntime,
workspaceSchemes
});
// Hydrate the heavy logger implementation in background (does not block activation)
(async () => {
try {
const { getFeatureFlagsGlobal } = require('./src/utils/featureFlagsBridge');
const featureFlagsGlobal = getFeatureFlagsGlobal();
const chunk = featureFlagsGlobal ? await featureFlagsGlobal.loadFeatureModule('loggerImpl') : null;
if (chunk && typeof chunk.getOrCreateLogger === 'function') {
try {
const real = chunk.getOrCreateLogger();
const GLOBAL_LOGGER_KEY = '__explorerDatesLogger';
if (real) {
if (typeof global !== 'undefined') global[GLOBAL_LOGGER_KEY] = real;
else if (typeof globalThis !== 'undefined') globalThis[GLOBAL_LOGGER_KEY] = real;
}
} catch { /* ignore */ }
}
} catch { /* ignore */ }
})();
// Initialize and run settings migration
const settingsMigrationManager = new SettingsMigrationManager();
try {
await settingsMigrationManager.migrateAllSettings(context);
} catch (error) {
logger.warn('Settings migration encountered issues:', error);
}
const isWebUi = vscode.env.uiKind === vscode.UIKind.Web;
if (!isWebUi) {
try {
await settingsMigrationManager.autoOrganizeSettingsIfNeeded(context, {
trigger: 'activation',
silent: true
});
} catch (error) {
logger.warn('Settings organization encountered issues:', error);
}
} else {
logger.info('Skipping settings auto-organization in web runtime');
}
const isWeb = vscode.env.uiKind === vscode.UIKind.Web;
const featureConfig = vscode.workspace.getConfiguration('explorerDates');
// Use unified enableExportReporting setting (with fallback to legacy enableReporting)
const reportingEnabled = featureConfig.get('enableExportReporting',
featureConfig.get('enableReporting', true));
const apiEnabled = featureConfig.get('enableExtensionApi', true);
const onboardingEnabled = featureConfig.get('enableOnboardingSystem', true);
const analysisEnabled = featureConfig.get('enableAnalysisCommands', true);
const updateCommandContexts = async () => {
const config = vscode.workspace.getConfiguration('explorerDates');
const reporting = config.get('enableExportReporting', config.get('enableReporting', true));
const templates = config.get('enableWorkspaceTemplates', true);
const workspaceIntelligence = config.get('enableWorkspaceIntelligence', true);
const analysis = config.get('enableAnalysisCommands', true);
const extensionApi = config.get('enableExtensionApi', true);
const gitInsights = config.get('enableGitInsights', true) && !isWeb;
const isTrusted = typeof vscode.workspace.isTrusted !== 'undefined' ? vscode.workspace.isTrusted : true;
await vscode.commands.executeCommand('setContext', 'explorerDates.isWeb', isWeb);
await vscode.commands.executeCommand('setContext', 'explorerDates.isWorkspaceTrusted', isTrusted);
await vscode.commands.executeCommand('setContext', 'explorerDates.gitFeaturesAvailable', !isWeb);
await vscode.commands.executeCommand('setContext', 'explorerDates.gitCommandsAvailable', gitInsights);
await vscode.commands.executeCommand('setContext', 'explorerDates.exportReportingAvailable', reporting && !isWeb);
await vscode.commands.executeCommand('setContext', 'explorerDates.workspaceTemplatesAvailable', templates && !isWeb);
await vscode.commands.executeCommand('setContext', 'explorerDates.workspaceIntelligenceAvailable', workspaceIntelligence && !isWeb);
await vscode.commands.executeCommand('setContext', 'explorerDates.analysisCommandsAvailable', analysis && !isWeb);
await vscode.commands.executeCommand('setContext', 'explorerDates.extensionApiAvailable', extensionApi);
await vscode.commands.executeCommand('setContext', 'explorerDates.runtimeCommandsAvailable', !isWeb);
};
await updateCommandContexts();
context.subscriptions.push(vscode.workspace.onDidChangeConfiguration((event) => {
if (event.affectsConfiguration('explorerDates')) {
updateCommandContexts().catch((error) => {
logger.warn('Failed to update command contexts', error);
});
}
}));
// Update contexts when workspace trust changes
if (typeof vscode.workspace.onDidGrantWorkspaceTrust === 'function') {
context.subscriptions.push(vscode.workspace.onDidGrantWorkspaceTrust(() => {
updateCommandContexts().catch((error) => {
logger.warn('Failed to update command contexts after trust change', error);
});
}));
}
// Detect and set virtual workspace context (includes web + GitHub Repositories + other virtual FS)
const { isVirtualWorkspace } = require('./src/utils/virtualWorkspaceDetector');
const isVirtual = isVirtualWorkspace();
await vscode.commands.executeCommand('setContext', 'explorerDates.isVirtualWorkspace', isVirtual);
// Register file date decoration provider for overlay dates in Explorer
// Try to load a runtime chunk that contains the heavy provider implementation
let providerChunk = null;
try {
providerChunk = await (isWebEnvironment()
? chunkLoader._loadWebChunk('providerInit')
: chunkLoader.loadChunk('providerInit'));
if (providerChunk && typeof providerChunk.createFileDateDecorationProvider === 'function') {
if (isWebDiagnosticsEnabled()) {
diagLog('info', 'Provider factory located', { source: 'providerInit' });
}
if (isWeb) {
try {
await chunkLoader._loadWebChunk('fileDateProviderImplExport');
if (isWebDiagnosticsEnabled()) {
diagLog('info', 'Provider impl export chunk loaded', { chunkName: 'fileDateProviderImplExport' });
}
await chunkLoader._loadWebChunk('fileDateProviderImpl');
if (isWebDiagnosticsEnabled()) {
diagLog('info', 'Provider impl chunk loaded', { chunkName: 'fileDateProviderImpl' });
}
} catch (e) {
logger.warn('Failed to load provider impl chunk in web runtime', e?.message || e);
if (isWebDiagnosticsEnabled()) {
diagLog('warn', 'Provider impl chunk load failed', { error: e?.message || String(e) });
}
}
}
const factory = providerChunk.createFileDateDecorationProvider(context);
if (factory && typeof factory.createFileDateDecorationProvider === 'function') {
fileDateProvider = factory.createFileDateDecorationProvider();
if (isWebDiagnosticsEnabled()) {
recordProviderEvent('created', { source: 'providerInit' });
}
}
}
} catch (e) {
logger.warn('Failed to load fileDateProvider chunk, falling back to local provider', e?.message || e);
if (isWebDiagnosticsEnabled()) {
diagLog('warn', 'Provider chunk load failed', { error: e?.message || String(e) });
}
}
// Fallback to local synchronous provider implementation if chunk loading failed
if (!fileDateProvider) {
try {
// Use a dynamic require (via eval) so the provider implementation is not
// statically bundled into the main extension bundle. The provider has
// its own runtime chunk (`providerInit`) and should be lazily loaded.
const dynamicRequire = typeof eval === 'function' ? eval('require') : null;
// Avoid attempting to require source files in a web runtime — rely on web chunks instead.
if (!isWebEnvironment() && typeof dynamicRequire === 'function') {
const mod = dynamicRequire('./src/fileDateDecorationProvider');
const FileDateDecorationProvider = mod && (mod.FileDateDecorationProvider || mod.default || mod);
fileDateProvider = new FileDateDecorationProvider();
if (isWebDiagnosticsEnabled()) {
recordProviderEvent('created', { source: 'local' });
}
} else if (!isWebEnvironment()) {
const { FileDateDecorationProvider } = require('./src/fileDateDecorationProvider');
fileDateProvider = new FileDateDecorationProvider();
if (isWebDiagnosticsEnabled()) {
recordProviderEvent('created', { source: 'local' });
}
} else {
// Web runtime and no chunk available — leave fileDateProvider null to allow graceful degradation.
logger.warn('No FileDateDecorationProvider available for web runtime; some features may be disabled.');
if (isWebDiagnosticsEnabled()) {
diagLog('warn', 'Provider unavailable in web runtime');
}
}
} catch (e) {
logger.error('Failed to create FileDateDecorationProvider', e);
if (isWebDiagnosticsEnabled()) {
diagLog('error', 'Provider creation failed', { error: e?.message, stack: e?.stack });
}
throw e;
}
}
if (fileDateProvider) {
// Hydrate optional decoration helpers early so non-dev presets get full formatting/colors.
if (providerChunk && typeof providerChunk.hydrateProviderOptionalSystems === 'function') {
(async () => {
try { await providerChunk.hydrateProviderOptionalSystems(fileDateProvider); }
catch (err) { logger.debug('provider-init hydration failed', err); }
})();
if (isWebDiagnosticsEnabled()) {
recordProviderEvent('hydrated', { source: 'providerInit' });
}
}
try {
const decorationDisposable = vscode.window.registerFileDecorationProvider(fileDateProvider);
context.subscriptions.push(decorationDisposable);
logger.info('Explorer Dates: File decoration provider registered', {
isWeb: isWebRuntime,
remoteName
});
} catch (error) {
logger.error('Explorer Dates: Failed to register FileDecorationProvider', error);
}
context.subscriptions.push(fileDateProvider); // For proper disposal
context.subscriptions.push(logger); // Dispose logger on deactivation
if (isWebDiagnosticsEnabled()) {
recordProviderEvent('registered');
}
// Initialize advanced performance systems (best-effort)
try { await fileDateProvider.initializeAdvancedSystems(context); } catch (err) { logger.debug('FileDateDecorationProvider.initializeAdvancedSystems failed', err); }
// Check workspace size and prompt for performance mode if very large
try { await fileDateProvider.checkWorkspaceSize(); } catch (err) { logger.debug('FileDateDecorationProvider.checkWorkspaceSize failed', err); }
} else {
// Graceful degradation for web runtimes where the provider chunk may be absent
logger.warn('FileDateDecorationProvider unavailable — continuing without file decorations.');
if (isWebDiagnosticsEnabled()) {
diagLog('warn', 'Provider unavailable for decorations');
}
}
// Initialize managers lazily to reduce startup time and bundle size
let extensionApiManager = null;
let exportReportingRegistered = false;
// Helper functions for lazy loading
const getExtensionApiManager = async () => {
if (!apiEnabled) {
throw new Error('Extension API is disabled via explorerDates.enableExtensionApi');
}
if (!extensionApiManager) {
extensionApiManager = await ensureExtensionApiManager(context);
if (extensionApiManager && context.subscriptions) {
context.subscriptions.push(extensionApiManager);
}
}
return extensionApiManager;
};
const getExportReportingManager = async () => {
if (!reportingEnabled) {
throw new Error('Reporting is disabled via explorerDates.enableExportReporting');
}
if (!exportReportingRegistered) {
const config = vscode.workspace.getConfiguration('explorerDates');
const performanceMode = config.get('performanceMode', false);
const lightweightMode = env.EXPLORER_DATES_LIGHTWEIGHT_MODE === '1';
if (performanceMode || lightweightMode) {
logger.warn('Initializing Export Reporting Manager while performance/lightweight mode is active; activity tracking will remain suppressed.');
}
}
const manager = await ensureExportReportingManager(context);
if (manager && !exportReportingRegistered) {
context.subscriptions.push(manager);
exportReportingRegistered = true;
}
return manager;
};
// Expose public API for other extensions (lazy)
let cachedApi = null;
let apiPromise = null;
const apiFactory = async () => {
if (!apiPromise) {
apiPromise = (async () => {
const manager = await getExtensionApiManager();
cachedApi = manager ? manager.getApi() : null;
return cachedApi;
})();
}
return apiPromise;
};
if (apiEnabled) {
// Maintain synchronous compatibility: export function, not call result
context.exports = apiFactory;
// Also expose async version for future use
context.exportsAsync = apiFactory;
} else {
context.exports = undefined;
context.exportsAsync = undefined;
logger.info('Explorer Dates API exports disabled via explorerDates.enableExtensionApi');
}
// Show onboarding if needed without eagerly loading the heavy chunk for users who have already completed it.
const showWelcomeOnStartup = featureConfig.get('showWelcomeOnStartup', true);
if (onboardingEnabled && showWelcomeOnStartup) {