forked from teambit/bit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworkspace.ts
More file actions
2766 lines (2507 loc) · 110 KB
/
Copy pathworkspace.ts
File metadata and controls
2766 lines (2507 loc) · 110 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
/* eslint-disable max-lines */
import { parse } from 'comment-json';
import mapSeries from 'p-map-series';
import pMap from 'p-map';
import { Graph, Node, Edge } from '@teambit/graph.cleargraph';
import type { IssuesList } from '@teambit/component-issues';
import type { AspectLoaderMain, AspectDefinition } from '@teambit/aspect-loader';
import { generateNodeModulesPattern, PatternTarget } from '@teambit/dependencies.modules.packages-excluder';
import type {
ComponentMain,
Component,
ComponentFactory,
InvalidComponent,
ResolveAspectsOptions,
AspectList,
} from '@teambit/component';
import { AspectEntry } from '@teambit/component';
import { BitError } from '@teambit/bit-error';
import type { ComponentScopeDirMap, ConfigMain, WorkspaceConfig } from '@teambit/config';
import type {
CurrentPkg,
DependencyResolverMain,
DependencyList,
VariantPolicyConfigObject,
VariantPolicyConfigArr,
WorkspacePolicyEntry,
} from '@teambit/dependency-resolver';
import { DependencyResolverAspect, VariantPolicy } from '@teambit/dependency-resolver';
import type { EnvsMain, EnvJsonc } from '@teambit/envs';
import { EnvsAspect } from '@teambit/envs';
import type { GraphqlMain } from '@teambit/graphql';
import type { Harmony } from '@teambit/harmony';
import type { Logger } from '@teambit/logger';
import type { ScopeMain } from '@teambit/scope';
import { isMatchNamespacePatternItem } from '@teambit/workspace.modules.match-pattern';
import type { VariantsMain } from '@teambit/variants';
import type { ComponentIdObj } from '@teambit/component-id';
import { ComponentID, ComponentIdList } from '@teambit/component-id';
import { InvalidScopeName, InvalidScopeNameFromRemote, isValidScopeName, BitId } from '@teambit/legacy-bit-id';
import type { LaneId } from '@teambit/lane-id';
import type { Consumer } from '@teambit/legacy.consumer';
import { loadConsumer } from '@teambit/legacy.consumer';
import type { GetBitMapComponentOptions } from '@teambit/legacy.bit-map';
import { MissingBitMapComponent } from '@teambit/legacy.bit-map';
import type { InMemoryCache } from '@teambit/harmony.modules.in-memory-cache';
import { getMaxSizeForComponents, createInMemoryCache } from '@teambit/harmony.modules.in-memory-cache';
import { ComponentsList } from '@teambit/legacy.component-list';
import type { ExtensionDataEntry } from '@teambit/legacy.extension-data';
import { ExtensionDataList, REMOVE_EXTENSION_SPECIAL_SIGN } from '@teambit/legacy.extension-data';
import type { PathOsBased, PathOsBasedRelative, PathOsBasedAbsolute } from '@teambit/toolbox.path.path';
import { pathNormalizeToLinux } from '@teambit/toolbox.path.path';
import { isPathInside } from '@teambit/toolbox.path.is-path-inside';
import fs from 'fs-extra';
import type { CompIdGraph, DepEdgeType } from '@teambit/graph';
import { slice, isEmpty, merge, compact, uniqBy, uniq } from 'lodash';
import { MergeConfigFilename, BIT_ROOTS_DIR, CFG_DEFAULT_RESOLVE_ENVS_FROM_ROOTS } from '@teambit/legacy.constants';
import path from 'path';
import type { Dependency as LegacyDependency } from '@teambit/legacy.consumer-component';
import { ConsumerComponent } from '@teambit/legacy.consumer-component';
import type { WatchOptions } from '@teambit/watcher';
import type { ComponentLog, Lane } from '@teambit/objects';
import type { JsonVinyl } from '@teambit/component.sources';
import { SourceFile, DataToPersist, PackageJsonFile } from '@teambit/component.sources';
import { ScopeComponentsImporter, VersionNotFoundOnFS } from '@teambit/legacy.scope';
import { LaneNotFound } from '@teambit/legacy.scope-api';
import { ScopeNotFoundOrDenied } from '@teambit/scope.remotes';
import { isHash } from '@teambit/component-version';
import type { GlobalConfigMain } from '@teambit/global-config';
import { ComponentConfigFile } from './component-config-file';
import type {
OnComponentAdd,
OnComponentChange,
OnComponentEventResult,
OnComponentLoad,
OnComponentRemove,
SerializableResults,
} from './on-component-events';
import type { WorkspaceExtConfig } from './types';
import { ComponentStatus } from './workspace-component/component-status';
import type {
OnAspectsResolve,
OnAspectsResolveSlot,
OnBitmapChange,
OnBitmapChangeSlot,
OnWorkspaceConfigChange,
OnWorkspaceConfigChangeSlot,
OnComponentAddSlot,
OnComponentChangeSlot,
OnComponentLoadSlot,
OnComponentRemoveSlot,
OnRootAspectAdded,
OnRootAspectAddedSlot,
} from './workspace.main.runtime';
import type { ComponentLoadOptions } from './workspace-component/workspace-component-loader';
import { WorkspaceComponentLoader } from './workspace-component/workspace-component-loader';
import type { ShouldLoadFunc } from './build-graph-from-fs';
import { GraphFromFsBuilder } from './build-graph-from-fs';
import { BitMap } from './bit-map';
import type { MergeOptions as BitmapMergeOptions } from './bit-map';
import { WorkspaceAspect } from './workspace.aspect';
import { GraphIdsFromFsBuilder } from './build-graph-ids-from-fs';
import { AspectsMerger } from './aspects-merger';
import type {
AspectPackage,
GetConfiguredUserAspectsPackagesOptions,
WorkspaceLoadAspectsOptions,
} from './workspace-aspects-loader';
import { WorkspaceAspectsLoader } from './workspace-aspects-loader';
import type { MergeConflictFile } from './merge-conflict-file';
import { MergeConfigConflict } from './exceptions/merge-config-conflict';
import { CompFiles } from './workspace-component/comp-files';
import { Filter } from './filter';
import type { ComponentStatusLegacy, ComponentStatusResult } from './workspace-component/component-status-loader';
import { ComponentStatusLoader } from './workspace-component/component-status-loader';
import execa from 'execa';
import { getGitExecutablePath } from '@teambit/git.modules.git-executable';
import { VERSION_ZERO } from '@teambit/objects';
import { getAutoTagInfo, getAutoTagPending } from './auto-tag';
import type { ConfigStoreMain, Store } from '@teambit/config-store';
import { ConfigStoreAspect } from '@teambit/config-store';
import type { DependenciesOverridesData } from '@teambit/legacy.consumer-config';
export type EjectConfResult = {
configPath: string;
};
export type ClearCacheOptions = {
skipClearFailedToLoadEnvs?: boolean;
};
/**
* Field used to mark aspect config as "specific" (set via .bitmap or component.json).
* When __specific is true, this config takes precedence over workspace variants during merging.
* See https://github.com/teambit/bit/pull/5342 for original implementation.
*
* Important behavior for dependency-resolver aspect:
* - Dependencies set via workspace variants are saved WITHOUT __specific (until first `bit deps set`)
* - Once `bit deps set` is called, the entire dependency-resolver config gets __specific: true
* - From that point forward, ALL deps in that aspect are considered "specific"
*/
export const AspectSpecificField = '__specific';
export const ComponentAdded = 'componentAdded';
export const ComponentChanged = 'componentChanged';
export const ComponentRemoved = 'componentRemoved';
export interface EjectConfOptions {
propagate?: boolean;
override?: boolean;
}
export type ComponentExtensionsOpts = {
loadExtensions?: boolean;
};
type ComponentExtensionsResponse = {
extensions: ExtensionDataList;
beforeMerge: Array<{ extensions: ExtensionDataList; origin: ExtensionsOrigin; extraData: any }>; // useful for debugging
errors?: Error[];
envId?: string;
};
export type ExtensionsOrigin =
| 'BitmapFile'
| 'ModelSpecific'
| 'ModelNonSpecific'
| 'ConfigMerge'
| 'WorkspaceVariants'
| 'ComponentJsonFile'
| 'FinalAfterMerge';
const DEFAULT_VENDOR_DIR = 'vendor';
/**
* API of the Bit Workspace
*/
export class Workspace implements ComponentFactory {
private warnedAboutMisconfiguredEnvs: string[] = []; // cache env-ids that have been errored about not having "env" type
priority = true;
owner?: string;
componentsScopeDirsMap: ComponentScopeDirMap;
componentLoader: WorkspaceComponentLoader;
private componentStatusLoader: ComponentStatusLoader;
bitMap: BitMap;
/**
* Indicate that we are now running installation process
* This is important to know to ignore missing modules across different places
*/
inInstallContext = false;
/**
* Indicate that we done with the package manager installation process
* This is important to skip stuff when package manager install is not done yet
*/
inInstallAfterPmContext = false;
private componentLoadedSelfAsAspects: InMemoryCache<boolean>; // cache loaded components
private aspectsMerger: AspectsMerger;
/**
* Components paths are calculated from the component package names of the workspace
* They are used in webpack configuration to only track changes from these paths inside `node_modules`
*/
private componentPathsRegExps: RegExp[] = [];
private _componentList: ComponentsList;
localAspects: Record<string, string> = {};
filter: Filter;
constructor(
private config: WorkspaceExtConfig,
/**
* private access to the legacy consumer instance.
*/
public consumer: Consumer,
/**
* access to the workspace `Scope` instance
*/
readonly scope: ScopeMain,
/**
* access to the `ComponentProvider` instance
*/
private componentAspect: ComponentMain,
private dependencyResolver: DependencyResolverMain,
readonly variants: VariantsMain,
private aspectLoader: AspectLoaderMain,
readonly logger: Logger,
/**
* private reference to the instance of Harmony.
*/
private harmony: Harmony,
/**
* on component load slot.
*/
public onComponentLoadSlot: OnComponentLoadSlot,
/**
* on component change slot.
*/
private onComponentChangeSlot: OnComponentChangeSlot,
readonly envs: EnvsMain,
readonly globalConfig: GlobalConfigMain,
/**
* on component add slot.
*/
private onComponentAddSlot: OnComponentAddSlot,
private onComponentRemoveSlot: OnComponentRemoveSlot,
private onAspectsResolveSlot: OnAspectsResolveSlot,
private onRootAspectAddedSlot: OnRootAspectAddedSlot,
private graphql: GraphqlMain,
private onBitmapChangeSlot: OnBitmapChangeSlot,
private onWorkspaceConfigChangeSlot: OnWorkspaceConfigChangeSlot,
private configStore: ConfigStoreMain
) {
this.componentLoadedSelfAsAspects = createInMemoryCache({ maxSize: getMaxSizeForComponents() });
this.componentLoader = new WorkspaceComponentLoader(this, logger, dependencyResolver, envs, aspectLoader);
this.validateConfig();
this.bitMap = new BitMap(this.consumer.bitMap, this.consumer);
this.aspectsMerger = new AspectsMerger(this, this.harmony);
this.filter = new Filter(this);
this.componentStatusLoader = new ComponentStatusLoader(this);
}
private validateConfig() {
if (this.consumer.isLegacy) return;
if (isEmpty(this.config))
throw new BitError(
`fatal: workspace config is empty. probably one of bit files is missing. please run "bit init" to rewrite them`
);
const defaultScope = this.config.defaultScope;
if (!defaultScope) throw new BitError('defaultScope is missing');
if (!isValidScopeName(defaultScope)) throw new InvalidScopeName(defaultScope);
}
get componentList(): ComponentsList {
if (!this._componentList) {
this._componentList = new ComponentsList(this);
}
return this._componentList;
}
/**
* root path of the Workspace.
*/
get path() {
return this.consumer.getPath();
}
/**
* Get the location of the bit roots folder
*/
get rootComponentsPath() {
const baseDir =
this.config.rootComponentsDirectory != null
? path.join(this.path, this.config.rootComponentsDirectory)
: this.modulesPath;
return path.join(baseDir, BIT_ROOTS_DIR);
}
/**
* Whether the workspace is configured to use root components — the per-env install
* layout written to `rootComponentsPath` (defaults to `node_modules/.bit_roots`,
* relocatable via `dependencyResolver.rootComponentsDirectory`).
*/
hasRootComponents(): boolean {
return this.dependencyResolver.hasRootComponents();
}
/** get the `node_modules` folder of this workspace */
private get modulesPath() {
return path.join(this.path, 'node_modules');
}
get isLegacy(): boolean {
return this.consumer.isLegacy;
}
registerOnComponentLoad(loadFn: OnComponentLoad) {
this.onComponentLoadSlot.register(loadFn);
return this;
}
registerOnComponentChange(onComponentChangeFunc: OnComponentChange) {
this.onComponentChangeSlot.register(onComponentChangeFunc);
return this;
}
registerOnComponentAdd(onComponentAddFunc: OnComponentAdd) {
this.onComponentAddSlot.register(onComponentAddFunc);
return this;
}
registerOnComponentRemove(onComponentRemoveFunc: OnComponentRemove) {
this.onComponentRemoveSlot.register(onComponentRemoveFunc);
return this;
}
registerOnBitmapChange(OnBitmapChangeFunc: OnBitmapChange) {
this.onBitmapChangeSlot.register(OnBitmapChangeFunc);
return this;
}
registerOnWorkspaceConfigChange(onWorkspaceConfigChangeFunc: OnWorkspaceConfigChange) {
this.onWorkspaceConfigChangeSlot.register(onWorkspaceConfigChangeFunc);
}
registerOnAspectsResolve(onAspectsResolveFunc: OnAspectsResolve) {
this.onAspectsResolveSlot.register(onAspectsResolveFunc);
return this;
}
registerOnRootAspectAdded(onRootAspectAddedFunc: OnRootAspectAdded) {
this.onRootAspectAddedSlot.register(onRootAspectAddedFunc);
return this;
}
/**
* name of the workspace as configured in either `workspace.json`.
* defaults to workspace root directory name.
*/
get name() {
if (this.config.name) return this.config.name;
const tokenizedPath = this.path.split('/');
return tokenizedPath[tokenizedPath.length - 1];
}
get icon() {
return this.config.icon;
}
getConfigStore(): Store {
return {
list: () => this.getWorkspaceConfig().extension(ConfigStoreAspect.id, true) || {},
set: (key: string, value: string) => {
this.getWorkspaceConfig().setExtension(
ConfigStoreAspect.id,
{ [key]: value },
{ ignoreVersion: true, mergeIntoExisting: true }
);
},
del: (key: string) => {
const current = this.getWorkspaceConfig().extension(ConfigStoreAspect.id, true) || {};
delete current[key];
this.getWorkspaceConfig().setExtension(ConfigStoreAspect.id, current, {
ignoreVersion: true,
overrideExisting: true,
});
},
write: async () => {
await this.getWorkspaceConfig().write({ reasonForChange: 'store-config changes' });
},
invalidateCache: async () => {
// no need to invalidate anything.
// if this is the same process, it'll get the updated one already.
// if this is another process, it'll react to "this.triggerOnWorkspaceConfigChange()" anyway.
},
getPath: () => this.getWorkspaceConfig().path,
};
}
async getAutoTagInfo(changedComponents: ComponentIdList) {
return getAutoTagInfo(this.consumer, changedComponents);
}
async listAutoTagPendingComponentIds(): Promise<ComponentID[]> {
const componentsList = new ComponentsList(this);
const modifiedComponents = (await this.modified()).map((c) => c.id);
const newComponents = (await componentsList.listNewComponents()) as ComponentIdList;
if (!modifiedComponents || !modifiedComponents.length) return [];
const autoTagPending = await getAutoTagPending(this.consumer, ComponentIdList.fromArray(modifiedComponents));
const localOnly = this.listLocalOnly();
const comps = autoTagPending
.filter((autoTagComp) => !newComponents.has(autoTagComp.componentId))
.filter((autoTagComp) => !localOnly.has(autoTagComp.componentId));
return comps.map((c) => c.id);
}
async hasModifiedDependencies(component: Component) {
const listAutoTagPendingComponents = await this.listAutoTagPendingComponentIds();
const isAutoTag = listAutoTagPendingComponents.find((id) => id.isEqualWithoutVersion(component.id));
if (isAutoTag) return true;
return false;
}
/**
* get Component issues
*/
getComponentIssues(component: Component): IssuesList | null {
return component.state._consumer.issues || null;
}
/**
* provides status of all components in the workspace.
*/
async getComponentStatus(component: Component): Promise<ComponentStatus> {
const status = await this.getComponentStatusById(component.id);
const hasModifiedDependencies = await this.hasModifiedDependencies(component);
return ComponentStatus.fromLegacy(status, hasModifiedDependencies, component.isOutdated());
}
/**
* list all workspace components.
*/
async list(filter?: { offset: number; limit: number }, loadOpts?: ComponentLoadOptions): Promise<Component[]> {
const loadOptsWithDefaults: ComponentLoadOptions = Object.assign(loadOpts || {});
const ids = this.consumer.bitMap.getAllIdsAvailableOnLane();
const idsToGet = filter && filter.limit ? slice(ids, filter.offset, filter.offset + filter.limit) : ids;
return this.getMany(idsToGet, loadOptsWithDefaults);
}
async listWithInvalid(loadOpts?: ComponentLoadOptions) {
const legacyIds = this.consumer.bitMap.getAllIdsAvailableOnLane();
return this.componentLoader.getMany(legacyIds, loadOpts, false);
}
/**
* list all invalid components.
* (see the invalid criteria in ConsumerComponent.isComponentInvalidByErrorType())
*/
async listInvalid(): Promise<InvalidComponent[]> {
const ids = this.consumer.bitMap.getAllIdsAvailableOnLane();
return this.componentLoader.getInvalid(ids);
}
/**
* get ids of all workspace components.
* deleted components are filtered out. (use this.listIdsIncludeRemoved() if you need them)
*/
listIds(): ComponentIdList {
return this.consumer.bitmapIdsFromCurrentLane;
}
listIdsIncludeRemoved(): ComponentIdList {
return this.consumer.bitmapIdsFromCurrentLaneIncludeRemoved;
}
/**
* whether the given component-id is part of the workspace. default to check for the exact version
*/
hasId(componentId: ComponentID, opts?: { includeDeleted?: boolean; ignoreVersion?: boolean }): boolean {
const ids = opts?.includeDeleted ? this.listIdsIncludeRemoved() : this.listIds();
return opts?.ignoreVersion ? ids.hasWithoutVersion(componentId) : ids.has(componentId);
}
/**
* given component-ids, return the ones that are part of the workspace
*/
async filterIds(ids: ComponentID[]): Promise<ComponentID[]> {
const workspaceIds = this.listIds();
return ids.filter((id) => workspaceIds.find((wsId) => wsId.isEqual(id, { ignoreVersion: !id.hasVersion() })));
}
/**
* whether or not a workspace has a component with the given name
*/
async hasName(name: string): Promise<boolean> {
const ids = await this.listIds();
return Boolean(ids.find((id) => id.fullName === name));
}
/**
* Check if a specific id exist in the workspace or in the scope
* @param componentId
*/
async hasIdNested(componentId: ComponentID, includeCache = true): Promise<boolean> {
const found = await this.hasId(componentId);
if (found) return found;
return this.scope.hasIdNested(componentId, includeCache);
}
/**
* list all modified components in the workspace.
*/
async modified(loadOpts?: ComponentLoadOptions): Promise<Component[]> {
const { components } = await this.listWithInvalid(loadOpts);
const modifiedIncludeNulls = await mapSeries(components, async (component) => {
const modified = await this.isModified(component);
return modified ? component : null;
});
return compact(modifiedIncludeNulls);
}
/**
* list all new components in the workspace.
*/
async newComponents() {
const componentIds = await this.newComponentIds();
return this.getMany(componentIds);
}
async newComponentIds(): Promise<ComponentID[]> {
const allIds = this.listIds();
return allIds.filter((id) => !id.hasVersion());
}
async locallyDeletedIds(): Promise<ComponentID[]> {
return this.componentList.listLocallySoftRemoved();
}
async duringMergeIds(): Promise<ComponentID[]> {
const duringMerge = this.componentList.listDuringMergeStateComponents();
return this.resolveMultipleComponentIds(duringMerge);
}
/**
* @deprecated use `listIds()` instead.
* get all workspace component-ids
*/
getAllComponentIds(): ComponentID[] {
return this.listIds();
}
async listTagPendingIds(): Promise<ComponentID[]> {
const newComponents = await this.newComponentIds();
const modifiedComponents = (await this.modified()).map((c) => c.id);
const removedComponents = await this.locallyDeletedIds();
const duringMergeIds = await this.duringMergeIds();
const allIds = [...newComponents, ...modifiedComponents, ...removedComponents, ...duringMergeIds];
const allIdsUniq = uniqBy(allIds, (id) => id.toString());
return allIdsUniq;
}
/**
* list all components that can be tagged. (e.g. when tagging/snapping with --unmodified).
* which are all components in the workspace, include locally deleted components.
*/
async listPotentialTagIds(): Promise<ComponentID[]> {
const deletedIds = await this.locallyDeletedIds();
const allIdsWithoutDeleted = this.listIds();
return [...deletedIds, ...allIdsWithoutDeleted];
}
async getNewAndModifiedIds(): Promise<ComponentID[]> {
const ids = await this.listTagPendingIds();
return ids;
}
async newAndModified(): Promise<Component[]> {
const ids = await this.getNewAndModifiedIds();
return this.getMany(ids);
}
async getLogs(id: ComponentID, shortHash = false, startsFrom?: string): Promise<ComponentLog[]> {
return this.scope.getLogs(id, shortHash, startsFrom);
}
async getGraph(ids?: ComponentID[], shouldThrowOnMissingDep = true): Promise<Graph<Component, string>> {
if (!ids || ids.length < 1) ids = this.listIds();
return this.buildOneGraphForComponents(ids, undefined, undefined, shouldThrowOnMissingDep);
}
async getGraphIds(ids?: ComponentID[], shouldThrowOnMissingDep = true): Promise<CompIdGraph> {
if (!ids || ids.length < 1) ids = this.listIds();
const graphIdsFromFsBuilder = new GraphIdsFromFsBuilder(
this,
this.logger,
this.dependencyResolver,
shouldThrowOnMissingDep
);
return graphIdsFromFsBuilder.buildGraph(ids);
}
async getUnavailableOnMainComponents(): Promise<ComponentID[]> {
const currentLaneId = this.consumer.getCurrentLaneId();
if (!currentLaneId.isDefault()) return [];
const allIds = this.consumer.bitMap.getAllBitIdsFromAllLanes();
const availableIds = this.consumer.bitMap.getAllIdsAvailableOnLane();
if (allIds.length === availableIds.length) return [];
const unavailableIds = allIds.filter((id) => !availableIds.hasWithoutVersion(id));
if (!unavailableIds.length) return [];
const removedIds = this.consumer.bitMap.getRemoved();
const compsWithHead: ComponentID[] = [];
await Promise.all(
unavailableIds.map(async (id) => {
if (removedIds.has(id)) return; // we don't care about removed components
const modelComp = await this.scope.legacyScope.getModelComponentIfExist(id);
if (modelComp && modelComp.head) compsWithHead.push(id);
})
);
return compsWithHead;
}
getDependencies(component: Component): DependencyList {
return this.dependencyResolver.getDependencies(component);
}
async getSavedGraphOfComponentIfExist(component: Component) {
if (!component.id.hasVersion()) return null;
const flattenedEdges = await this.scope.getFlattenedEdges(component.id);
const versionObj = await this.scope.getBitObjectVersionById(component.id);
if (!flattenedEdges || !versionObj) return null;
if (!flattenedEdges.length && versionObj.flattenedDependencies.length) {
// there are flattenedDependencies, so must be edges, if they're empty, it's because the component was tagged
// with a version < ~0.0.901, so this flattenedEdges wasn't exist.
return null;
}
const flattenedBitIdCompIdMap: { [bitIdStr: string]: ComponentID } = {};
const getCurrentVersionAsTagIfPossible = (): string | undefined => {
const currentVer = component.id.version;
if (!currentVer) return undefined;
const isCurrentVerAHash = isHash(currentVer);
if (!isCurrentVerAHash) return currentVer;
const tag = component.tags.byHash(currentVer)?.version.raw;
return tag || currentVer;
};
const currentVersion = getCurrentVersionAsTagIfPossible();
flattenedBitIdCompIdMap[component.id.changeVersion(currentVersion).toString()] = component.id;
versionObj.flattenedDependencies.forEach((bitId) => {
flattenedBitIdCompIdMap[bitId.toString()] = bitId;
});
const getCompIdByIdStr = (idStr: string): ComponentID => {
const compId = flattenedBitIdCompIdMap[idStr];
if (!compId) {
const suggestWrongSnap = isHash(component.id.version)
? `\nplease check that .bitmap has the correct versions of ${component.id.toStringWithoutVersion()}.
it's possible that the version ${component.id.version} belong to ${idStr.split('@')[0]}`
: '';
throw new Error(
`id ${idStr} exists in flattenedEdges but not in flattened of ${component.id.toString()}.${suggestWrongSnap}`
);
}
return compId;
};
const nodes = Object.values(flattenedBitIdCompIdMap);
const edges = flattenedEdges.map((edge) => ({
...edge,
source: getCompIdByIdStr(edge.source.toString()),
target: getCompIdByIdStr(edge.target.toString()),
}));
const graph = new Graph<ComponentID, DepEdgeType>();
nodes.forEach((node) => graph.setNode(new Node(node.toString(), node)));
edges.forEach((edge) => graph.setEdge(new Edge(edge.source.toString(), edge.target.toString(), edge.type)));
return graph;
}
/**
* given component ids, find their dependents in the workspace
*/
async getDependentsIds(ids: ComponentID[], filterOutNowWorkspaceIds = true): Promise<ComponentID[]> {
const graph = await this.getGraphIds();
const dependents = ids
.map((id) =>
graph.predecessors(id.toString(), {
nodeFilter: (node) => (filterOutNowWorkspaceIds ? this.hasId(node.attr) : true),
})
)
.flat()
.map((node) => node.attr);
return ComponentIdList.uniqFromArray(dependents);
}
public async createAspectList(extensionDataList: ExtensionDataList) {
const entiresP = extensionDataList.map((entry) => this.extensionDataEntryToAspectEntry(entry));
const entries: AspectEntry[] = await Promise.all(entiresP);
return this.componentAspect.createAspectListFromEntries(entries);
}
private async extensionDataEntryToAspectEntry(dataEntry: ExtensionDataEntry): Promise<AspectEntry> {
return new AspectEntry(await this.resolveComponentId(dataEntry.id), dataEntry);
}
/**
* this is not the complete legacy component (ConsumerComponent), it's missing dependencies and hooks from Harmony
* are skipped. do not trust the data you get from this method unless you know what you're doing.
*/
async getLegacyMinimal(id: ComponentID): Promise<ConsumerComponent | undefined> {
try {
const componentMap = this.consumer.bitMap.getComponent(id);
return await ConsumerComponent.loadFromFileSystem({
componentMap,
id,
consumer: this.consumer,
});
} catch {
return undefined;
}
}
async getFilesModification(id: ComponentID): Promise<CompFiles> {
const bitMapEntry = this.bitMap.getBitmapEntry(id, { ignoreVersion: true });
const compDir = bitMapEntry.getComponentDir();
const compDirAbs = path.join(this.path, compDir);
const sourceFilesVinyls = bitMapEntry.files.map((file) => {
const filePath = path.join(compDirAbs, file.relativePath);
return SourceFile.load(filePath, compDirAbs, this.path, {});
});
const repo = this.scope.legacyScope.objects;
const getModelFiles = async () => {
const modelComp = await this.scope.legacyScope.getModelComponentIfExist(id);
if (!modelComp) return [];
if (!bitMapEntry.id.hasVersion()) return [];
const verObj = await modelComp.loadVersion(bitMapEntry.id.version, repo);
return verObj.files;
};
return new CompFiles(id, repo, sourceFilesVinyls, compDir, await getModelFiles());
}
/**
* get a component from workspace
* @param id component ID
*/
async get(
componentId: ComponentID,
legacyComponent?: ConsumerComponent,
useCache = true,
storeInCache = true,
loadOpts?: ComponentLoadOptions
): Promise<Component> {
this.logger.trace(`get ${componentId.toString()}`);
const component = await this.componentLoader.get(componentId, legacyComponent, useCache, storeInCache, loadOpts);
// When loading a component if it's an env make sure to load it as aspect as well
// We only want to try load it as aspect if it's the first time we load the component
const tryLoadAsAspect = this.componentLoadedSelfAsAspects.get(component.id.toString()) === undefined;
// const config = this.harmony.get<ConfigMain>('teambit.harmony/config');
// We are loading the component as aspect if it's an env, in order to be able to run the env-preview-template task which run only on envs.
// Without this loading we will have a problem in case the env is the only component in the workspace. in that case we will load it as component
// then we don't run it's provider so it doesn't register to the env slot, so we don't know it's an env.
if (
tryLoadAsAspect &&
this.envs.isUsingEnvEnv(component) &&
!this.aspectLoader.isCoreAspect(component.id.toStringWithoutVersion()) &&
!this.aspectLoader.isAspectLoaded(component.id.toString()) &&
this.hasId(component.id)
// !config.extension(component.id.toStringWithoutVersion(), true)
) {
try {
this.componentLoadedSelfAsAspects.set(component.id.toString(), true);
this.logger.debug(`trying to load self as aspect with id ${component.id.toString()}`);
// ignore missing modules when loading self
await this.loadAspects([component.id.toString()], undefined, component.id.toString(), {
hideMissingModuleError: true,
});
// In most cases if the load self as aspect failed we don't care about it.
// we only need it in specific cases to work, but this workspace.get runs on different
// cases where it might fail (like when importing aspect, after the import objects
// when we write the package.json we run the applyTransformers which get to pkg which call
// host.get, but the component not written yet to the fs, so it fails.)
} catch {
this.logger.debug(`fail to load self as aspect with id ${component.id.toString()}`);
this.componentLoadedSelfAsAspects.delete(component.id.toString());
return component;
}
}
this.componentLoadedSelfAsAspects.set(component.id.toString(), false);
return component;
}
async getConfiguredUserAspectsPackages(options: GetConfiguredUserAspectsPackagesOptions): Promise<AspectPackage[]> {
const workspaceAspectsLoader = this.getWorkspaceAspectsLoader();
return workspaceAspectsLoader.getConfiguredUserAspectsPackages(options);
}
/**
* clears workspace, scope and all components caches.
* doesn't clear the dependencies-data from the filesystem-cache.
*/
async clearCache(options: ClearCacheOptions = {}) {
this.logger.debug('clearing the workspace and scope caches');
this.aspectLoader.resetFailedLoadAspects();
if (!options.skipClearFailedToLoadEnvs) this.envs.resetFailedToLoadEnvs();
await this.scope.clearCache();
this.clearAllComponentsCache();
}
/**
* clear the cache of all components in the workspace.
* doesn't clear the dependencies-data from the filesystem-cache.
*/
clearAllComponentsCache() {
this.logger.debug('clearing all components caches');
this.componentLoader.clearCache();
this.consumer.componentLoader.clearComponentsCache();
this.componentStatusLoader.clearCache();
this._componentList = new ComponentsList(this);
}
clearComponentCache(id: ComponentID) {
this.componentLoader.clearComponentCache(id);
this.componentStatusLoader.clearOneComponentCache(id);
this.consumer.clearOneComponentCache(id);
this._componentList = new ComponentsList(this);
}
clearComponentsCache(ids: ComponentID[]) {
ids.forEach((id) => this.clearComponentCache(id));
}
async warmCache() {
await this.list();
}
getWorkspaceConfig(): WorkspaceConfig {
const config = this.harmony.get<ConfigMain>('teambit.harmony/config');
const workspaceConfig = config.workspaceConfig;
if (!workspaceConfig) throw new Error('workspace config is missing from Config aspect');
return workspaceConfig;
}
async cleanFromConfig(ids: ComponentID[]) {
const workspaceConfig = this.getWorkspaceConfig();
const wereIdsRemoved = ids.map((id) => workspaceConfig.removeExtension(id));
const hasChanged = wereIdsRemoved.some((isRemoved) => isRemoved);
if (hasChanged) await workspaceConfig.write({ reasonForChange: 'remove components' });
return hasChanged;
}
/**
* when tagging/snapping a component, its config data is written to the staged config. it helps for "bit reset" to
* revert it back.
* this method removes entries from that files. used by "bit export" and "bit remove".
* in case the component is not found in the staged config, it doesn't throw an error. it simply ignores it.
*/
async removeFromStagedConfig(ids: ComponentID[]) {
this.logger.debug(`removeFromStagedConfig, ${ids.length} ids`);
const stagedConfig = await this.scope.getStagedConfig();
ids.map((compId) => stagedConfig.removeComponentConfig(compId));
await stagedConfig.write();
}
async triggerOnComponentChange(
id: ComponentID,
files: PathOsBasedAbsolute[],
removedFiles: PathOsBasedAbsolute[],
watchOpts: WatchOptions
): Promise<OnComponentEventResult[]> {
const component = await this.get(id);
const onChangeEntries = this.onComponentChangeSlot.toArray(); // e.g. [ [ 'teambit.bit/compiler', [Function: bound onComponentChange] ] ]
const results: Array<{ extensionId: string; results: SerializableResults }> = [];
await mapSeries(onChangeEntries, async ([extension, onChangeFunc]) => {
const onChangeResult = await onChangeFunc(component, files, removedFiles, watchOpts);
if (onChangeResult) results.push({ extensionId: extension, results: onChangeResult });
});
// TODO: find way to standardize event names.
await this.graphql.pubsub.publish(ComponentChanged, { componentChanged: { component } });
return results;
}
async triggerOnComponentAdd(
id: ComponentID,
watchOpts: WatchOptions,
loadOptions?: ComponentLoadOptions
): Promise<OnComponentEventResult[]> {
const component = await this.get(id, undefined, undefined, undefined, loadOptions);
const onAddEntries = this.onComponentAddSlot.toArray(); // e.g. [ [ 'teambit.bit/compiler', [Function: bound onComponentChange] ] ]
const results: Array<{ extensionId: string; results: SerializableResults }> = [];
const files = component.state.filesystem.files.map((file) => file.path);
await mapSeries(onAddEntries, async ([extension, onAddFunc]) => {
const onAddResult = await onAddFunc(component, files, watchOpts);
if (onAddResult) results.push({ extensionId: extension, results: onAddResult });
});
await this.graphql.pubsub.publish(ComponentAdded, { componentAdded: { component } });
return results;
}
async triggerOnComponentRemove(id: ComponentID): Promise<OnComponentEventResult[]> {
const onRemoveEntries = this.onComponentRemoveSlot.toArray(); // e.g. [ [ 'teambit.bit/compiler', [Function: bound onComponentChange] ] ]
const results: Array<{ extensionId: string; results: SerializableResults }> = [];
await mapSeries(onRemoveEntries, async ([extension, onRemoveFunc]) => {
const onRemoveResult = await onRemoveFunc(id);
results.push({ extensionId: extension, results: onRemoveResult });
});
await this.graphql.pubsub.publish(ComponentRemoved, { componentRemoved: { componentIds: [id.toObject()] } });
return results;
}
async triggerOnBitmapChange(): Promise<void> {
const onBitmapChangeEntries = this.onBitmapChangeSlot.toArray(); // e.g. [ [ 'teambit.bit/compiler', [Function: bound onComponentChange] ] ]
await mapSeries(onBitmapChangeEntries, async ([, onBitmapChangeFunc]) => {
await onBitmapChangeFunc();
});
}
/**
* the purpose is mostly to reload the workspace config when it changes, so entries like "defaultScope" are updated.
* it also updates the DependencyResolver config. I couldn't find a good way to update all aspects in workspace.jsonc.
*/
async triggerOnWorkspaceConfigChange(): Promise<void> {
this.logger.debug('triggerOnWorkspaceConfigChange, reloading workspace config');
const config = this.harmony.get<ConfigMain>('teambit.harmony/config');
await config.reloadWorkspaceConfig(this.path);
const workspaceConfig = config.workspaceConfig;
if (!workspaceConfig) throw new Error('workspace config is missing from Config aspect');
const configOfWorkspaceAspect = workspaceConfig.extensions.findExtension(WorkspaceAspect.id);
if (!configOfWorkspaceAspect) throw new Error('workspace extension is missing from workspace config');
this.config = configOfWorkspaceAspect.config as WorkspaceExtConfig;
const configOfDepResolverAspect = workspaceConfig.extensions.findExtension(DependencyResolverAspect.id);
if (configOfDepResolverAspect) this.dependencyResolver.setConfig(configOfDepResolverAspect.config as any);
this.dependencyResolver.clearCache();
this.configStore.invalidateCache();
const onWorkspaceConfigChangeEntries = this.onWorkspaceConfigChangeSlot.toArray(); // e.g. [ [ 'teambit.bit/compiler', [Function: bound onComponentChange] ] ]
await mapSeries(onWorkspaceConfigChangeEntries, async ([, onWorkspaceConfigFunc]) => {
await onWorkspaceConfigFunc();
});
}
getState(id: ComponentID, hash: string) {
return this.scope.getState(id, hash);
}
getSnap(id: ComponentID, hash: string) {
return this.scope.getSnap(id, hash);
}
getCurrentLaneId(): LaneId {
return this.consumer.getCurrentLaneId();
}
async getCurrentLaneObject(): Promise<Lane | undefined> {
return this.consumer.getCurrentLaneObject();
}
isOnMain(): boolean {
return this.consumer.isOnMain();
}
isOnLane(): boolean {
return this.consumer.isOnLane();
}
/**
* if checked out to a lane and the lane exists in the remote,
* return the remote lane. otherwise, return null.
*/
async getCurrentRemoteLane(): Promise<Lane | null> {
const currentLaneId = this.getCurrentLaneId();
if (currentLaneId.isDefault()) {
return null;
}
const scopeComponentImporter = ScopeComponentsImporter.getInstance(this.consumer.scope);
try {
const lanes = await scopeComponentImporter.importLanes([currentLaneId]);
return lanes[0];
} catch (err: any) {
if (
err instanceof InvalidScopeName ||